Tuesday, 25 October, 2016 UTC


Summary

Written on October 25th, 2016. No updates have been applied to the step by step application setup. This paragraph will always reflect the actuality of the article.
I recently started reviewing React applications of many software developers, who just got started writing React code. My common takeaway was that most developers don’t spend enough effort on creating their environment setup. The goal of this article is to act as a baseline for your application setup. Therefore, I will apply updates to this article on a regular basis.
When you read an article like this, always pay attention to the date when it was written. This is why I started the whole article with the date. Assuming the churn rate of JavaScript frameworks and libraries doesn’t slow down significantly, a three year old tutorial on this topic will be outdated without updates. Always pay attention to the date!
If your boilerplate is a year old, I suggest refreshing your knowledge. You may get some ideas about new things to try out.
You will also read about some major mistakes that developers make when it comes to installing modules globally, and failing to mention some dependencies.
We will first need Node, npm, and Git. Node and Git comes pre-installed in many operating systems already. If it is not the case for you, make sure you install them.

Step 1: Choose Your Text Editor or IDE

Technically, your editor is hardly ever a question in similar tutorials. It still makes sense to add this step to the list because of multiple reasons:
  • new promising contenders have emerged in the last two years
  • we need our editor to work with ES2015, and it should also support all syntactic sugar coming with React, namely, the JSX language
  • it is not obvious anymore which editor comes with the best developer experience
The goal of this step is not to give you an ultimate answer about which editor or IDE to choose. I will just enumerate some options you may have not heard about. I encourage you to do your own research, and customize your developer experience. Alternatively, you can just stick to your favorite for now, and wait for my article on comparing these four editors.
The most exhaustive list on IDEs and editors I have found is here. We will deal with the top four of the list. All four of them can be configured to work with ES2015 and React without problems and highlighting glitches.
WebStorm is the number one choice of most developers. It comes with a price tag of $129/year. Many people brag about the productivity boost WebStorm gives you, including coding assistance, full support for React, GIT integration, other tool integrations, and debugging utilities.
WebStorm is the only paid solution. All other editors may be used for free.
Visual Studio Code gained popularity lately. The main benefit of VS Code is IntelliSense, intelligent code completion. Debugging is also supported. The critics of Visual Studio Code say that IntelliSense makes it very slow and resource-intensive.
Atom and Sublime Text 3 have been around for a while. Atom’s advantage is Git integration. Sublime’s advantage has been stability and very wide support of additional packages. In fact, Sublime Text can do everything that all the other solutions can, if you install the right packages.
Even though it’s not on the list, one editor worth watching is Facebook’s Nuclide. Based on the list of releases, Nuclide is actively evolving. Even though it has not reached version 1 yet, it is worth watching Nuclide as a possible contender for the future.
Once you have selected the editor of your choice, make sure you configure it to work with ESLint.
In some editors, you have to configure it to use the correct syntax highlighting for React, ES2015, and JSX. For Sublime Text 3 for instance, you can use the package babel-sublime.

Step 2: Initialize your application

Create a folder for your new project. Execute npm init inside the folder of your application. Provide the necessary details about your application by answering the questions in the terminal. Once you are done answering or skipping these questions, a package.json file is created in your folder.

Step 3: Install Production Dependencies

Production dependencies are the ones that you use on production, not only during development.
Install the newest versions of React and ReactDOM:
npm install react react-dom --save
Once the installation is completed, package.json is automatically updated.
If you have experience with the earlier versions of React, the information may be new to you that the creators detached ReactDOM from React.
React and ReactDOM are generally used together. ReactDOM is a package for working with the DOM.

Step 4: Install Dev Dependencies

Dev dependencies are only used during development. They are not to be deployed when using your code in a production environment.
We will install the following dev dependencies:
  • babel-loader: babel module loader
  • babel-core: the core transpiler used for transpiling ES2015 and JSX code
  • babel-preset-es2015: ES6/ES2015 support
  • babel-preset-react: React/JSX support
  • babel-preset-stage-2: babel preset for some extra features such as destructuring
  • webpack: for bundling our packages for distribution and managing dependencies
  • webpack-dev-server: our development server
npm install webpack webpack-dev-server --save-dev

npm install babel-loader babel-core babel-preset-es2015 babel-preset-react babel-preset-stage-2 --save-dev
Many Frontend Developers think that including a development server is not necessary. After all, we just write HTML, CSS, and JavaScript, and all we need to do is to open our index.html file in the browser. Right? Wrong.
We will need some server side functionalities sooner or later. For instance, we need the http protocol to simulate state.
Webpack’s development server will do the trick.
If you are used to installing Babel, Webpack, or anything else globally, be aware that it is bad practice to do so. Imagine updating these dependencies, and these updates may break your dependency chain when a breaking change is not compatible with your setup.
Avoid global installations whenever you can. For instance, once I reviewed an application that wouldn’t work. After debugging, it turned out that a global dependency never made it to package.json. When I ran npm install, the dependency in question was never installed. If you create an open source application, chances are, most people downloading your application won’t be able to run it following your installation instructions.
Locally installing Babel or Webpack may come with path problems. If the command babel is not recognized by your operating system, don’t start adding path references. If you want to use Babel or Webpack, change your package.json instead by adding the following scripts:
"scripts": {
        "babel": "babel",      
        "webpack": "webpack" 
    }
You can run Babel and Webpack on its own by executing npm run babel and npm run webpack respectively.

Step 5: Create the Files of Your Application

Create a src folder, and create an app folder inside src.
Create our main HTML file, src/app/index.html. Generate or paste default HTML contents in the file. For instance, we can start with:
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React Boilerplate</title>
  </head>
  <body>
    <div class="js-app"></div>
  </body>
</html>
Create a JavaScript file in src/app. Name it app.js.
Import react and react-dom, and paste a simple demo component from the previous article. TODO: volt prev article??
import React from 'react';
import ReactDOM from 'react-dom'; 

var SimpleComponent = React.createClass({
   render: function() {
        return (
            <div>{this.props.message}</div>
        );
   } 
} );

ReactDOM.render(
    <SimpleComponent message="React Demo" />,
    document.querySelector( '.js-app' )
);

Step 6: Configure Webpack

The following Webpack config file will work with our application setup. Create a file webpack.config.js in your project folder on the same level where package.json is.
Paste the following contents, then read the explanation below to understand the settings.
var path = require('path');

var DIST_PATH = path.resolve( __dirname, 'dist' );
var SOURCE_PATH = path.resolve( __dirname, 'src' );

module.exports = {
    entry: SOURCE_PATH + '/app/app.js',
    output: {
        path: DIST_PATH,   
        filename: 'app.dist.js',
        publicPath: '/app/'
    },  
    module: {
        loaders: [
            {
                test: /.jsx?$/,  
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: [
                        'es2015',
                        'react',
                        'stage-2'
                    ]
                }
            }
        ]
    }
};
In line 1, path uses node’s built in ability to recognize the path of our application, and resolve the path of folders inside our application.
Our entry point in the application is /app/app.js.
The bundle file app.dist.js will be generated by Webpack. It contains our app code and all its dependencies. You don’t have to worry about referencing scripts in a certain order.
The path publicPath is important for the Webpack development server. We have to tell Webpack the location of the public server.
Place the reference to the bundle in your index.html file just before the end of the body:
<script src="/app/app.dist.js"></script>
Loaders compile all files matching the regular expression belonging to the test key. We have to transpile .js and .jsx files, that are matched by the provided regular expression.
The exclude key is for specifying folders to exclude. As node packages come already transpiled and minified, Webpack does not have to take care of them.
The list of presets are the same as the ones we installed with npm. Just remove the prefix babel-preset- from the name of the preset.

Step 7: Set up npm to build and run your application

Add two scripts to your package.json file to build the development version and the production version of your application.
"scripts": {
        // ...
        "build": "webpack -d && cp src/app/index.html dist/index.html && webpack-dev-server --hot --inline --colors --progress --content-base src/",
        "build-prod": "webpack -p && cp src/app/index.html dist/index.html"
    }
webpack -d runs Webpack in development mode, and webpack -p runs Webpack in production mode. In production mode, source maps are removed, and Webpack fully minifies the code.
We also have to copy the index.html file from the source folder to the dist folder. If you are using Windows, most likely you use cygwin, so the cp command is available to you. Otherwise, use copy instead of cp.
The last command in the -d build configures and runs the Webpack development server. It does hot compilation of the React code. As you write code, your browser is automatically refreshed. Remember, developer experience is always important, and these little tweaks save you a lot of time.
After entering npm run build in the terminal, you can reach your application in your browser, under the address http://localhost:8080. If you prefer another port, owerwrite it with the --port switch.
If you open localhost:8080/app, you can see the rendered component. Try modifying app.js by adding a string to the div you render on screen. After saving the file, watch the contents of your browser window reflect all changes in a second or so. Reloading the solution as you make changes to the source code adds a lot to the developer experience, if you try it out once, you won’t want to live without it anymore.
Lastly, if you would like to follow this tutorial, I encourage you to learn and practice the lastest JavaScript standards. Similarly to the environment setup, we will use the latest features that are available to us 2016-2017. I encourage you to stay up to date with ES6 by signing up for my email course. You will not only learn the fundamentals of ES6, but I will also give you exercises and reference solutions to practice the fundamentals. I strongly believe that your time is important, and therefore, you will learn exactly what’s needed for you in practice, nothing more, nothing less. If you expect a slightly different variation of the specification, feel free to buy any book or HD video course on ES6/ES2015, and you will get all information the specification gives you, bundled with some entertainment. If you want to put your skills into practice, sign up below by clicking the green YES button.
Would you like to learn ES6?
Strengthen your JavaScript knowledge with marketable skills!
YesORNo
Close
Get the Course "ES6 in Practice"!
Learn Marketable Skills.

Verify your knowledge with real world exercises.
I'm In!
Close
Thank you for your subscription.
Please check your inbox to access the first lesson.
Close