Getting Started: React app with Express server
To get started writing your application you eventually want to turn into a crud app, you would usually need to set up many files. First, let’s start by making a
package.json file. From the command line, cd into the directory you want to work with and run:
npm init -y
You should be able to see the new package.json file that you created. Next we will be installing the following dependencies:
* Express: The wrapper for your node server.
* React: The front-end framework of choice.
install --save express react react-dom
We will also be installing the following dev dependencies:
* Babel: For transpiling JSX and ES6 into ES5.
* CSS-loader, SASS-loader, Style-loader: For transpiling sass and css into our final js build file.
* Webpack: For our final build that will be served
* Mocha, Chai, Enzyme: This is optional. Use Whatever testing suite you are most comfortable with
install --save-dev babel babel-core babel-loader babel-preset-es2015 babel-preset-react css-loader node-sass sass-loader style-loader webpack mocha chai enzyme
Now let’s set up our
package.json. Add the following line inside of your scripts object
"start": "nodemon src/server/index.js",
"webpack": "./node_modules/.bin/webpack -w",
"test": "mocha --compilers babel-core/register ./test/*test.js"
If you don’t have nodemon installed globally, install using:
npm install -g nodemon
This will allow you to not have to restart your server every time you make a change to your files. Now lets create the following file structure:
/root (name of directory)
webpack.config.js , add the following lines of code:
Our webpack will start at
/src/client/index.js and will build into a
/src/server/index.js , add the following:
This is where your express server will live. Back in the root directory, in
index.html, set up some template html:
Notice that the html has a script pointing to our final
bundle.js file. Now we can finally move into our react app. Add these lines of code to each file:
Now that we have everything set up to build a react app lets run these two commands:
npm run webpack
And that’s it, you are ready to change the world, one React app at a time.