I love create-react-app
, I've used it to scaffold every new React app and React experiment I've worked on since it was released.
As I was updating one little hobby project (Markdown To Medium Tool) I built before Create React App I realized I wanted it to have the same webpack config, and the same npm scripts as all my more recent projects.
Dependencies
Most of the magic of Create React App is done by installing react-scripts
and adding it to package.json.
So I started by installing it to my old project:
npm install --save-dev react-scripts
NPM scripts
Next part was to peak into one of my Create React App projects and see what it had added to the scripts
section in package.json:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
Conventions
The last part that makes Create React App work is of course that every Create React App is set up the same.
A public
folder
There needs to be a public folder with an index.html
that looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
There should also be a favicon.ico
, but that doesn't seem super important...
root element
As you can see in the above html it adds an element with id root
, my previous app had an element with id app
.
I could change the id in the html but I changed document.querySelector('#app')
to #root
in my index.js
where I mount the app, since the point was to have it conform to the Create React App standards all my new.
ReactDOM.render(<App />, document.querySelector('#root'));
That's it! Running npm start
and npm build
now runs the react-scripts
and can build and serve the project perfectly. 🙌
This project didn't have any tests, if you have run of the mill jest tests and your test files are suffixed with .test.js
or .spec.js
it should work out of the box though.