Getting Started with React – Setting up the Development Environment

React (also React.js or ReactJS) is a JavaScript library for building user interfaces developed by Facebook & Instagram. It is not a full blown framework like Angular or Ember or even Backbone.js. It is a very simple View library which can replace the V in any other client-side MVC framework, i.e., you can use Backbone and React together for instance. In fact a lot of people are already doing that. Although when combined with a design pattern like Flux, you can totally give up on an MVC framework for your client-side architecture and happily develop apps with just React in conjunction with the Flux application architecture. React encompasses some interesting concepts too like Virtual DOM, uni-directional reactive data flow, etc. but don’t worry we’ll discuss all those much later when you’re already comfortable with the library and hacking your way through it.

I’ve decided to cover most of the React fundamentals in a series of articles, this being the first one. Now that you’ve already been introduced to React as a very simple yet powerful UI library, let’s dive deeper into how the setup has to be done before we can start building our apps.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Development Environment Setup

Before we actually get into setting up our React environment let me tell you that with most libraries or frameworks like jQuery, Bootstrap, Underscore, Angular, Backbone, etc. we’re used to just loading the main JS file with/without some additional assets right in the head section or before the body closes in our HTML code. This process is simple and straightforward.

In React you can definitely do something similar but with an npm (node package manager) based setup, you can have a much better and robust environment. It might seem a bit of a hassle or an unnecessarily large setup initially but you’ll get used to it over time and eventually like the power and flexibility of the setup.

Setup Without npm (Not Recommended)

Let me start off with the simpler method and then obviously explain why it is not recommended. So Facebook has uploaded starter kits for each react version on their github repository. Feel free to download and extract the latest zip. You’ll see two folders – build (has react javascript library files) and examples (has some example apps that you can play with later). Now for a quick setup/test you can create an index.html in the root of the folder with this piece of code:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>React App!</title>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello World!</h1>,
        document.getElementById('app')
      );
    </script>
  </body>
</html>

This is how your structure would be:

$ tree -L 1
.
├── README.md
├── build
├── examples
└── index.html

The react.js and react-dom.js are, you know well, the React libraries whereas the browser.min.js is Babel’s browser implementation. Babel is basically a next generation JavaScript compiler that lets you write code in ES2015 (ES6) and beyond, JSX, etc. which it eventually compiles down to basic JavaScript that can be understood and executed by all the browsers. In this case it’ll parse all the fancy code (ES6 and above, JSX, etc.) inside <script type="text/babel"> and compile that to ES5 so that the browser can execute it.

You’d be wondering what is this JSX I’m talking about or what is this piece of code that you see above:

ReactDOM.render(
  <h1>Hello World!</h1>,
  document.getElementById('app')
);

You don’t have to worry at all about this new syntax thinking you’ll have to learn a new language to code React. What you see is basically JSX (again developed by the same folks who built React), which is just an XML-like syntactical extension to ECMAScript (or JS). Just for understanding, it is to JS what probably Jade, HAML, ERB or Slim (templating languages) is to HTML (or even lesser).

In React, the idea was to generate HTML (as well as CSS) right from the JS code, instead of separating those concerns across different types of files altogether. I understand this seems weird right off the bat but don’t worry, as you dive deeper into it, you’ll start liking it and be able to detach yourself from the practise that we’ve been following for years – separate .html, .css and .js files.

So how would we exactly generate HTML from the JS code. We’d have to start making loads of calls to document.createElement('element'), node.setAttribute('attr', 'val'), etc. all across our JS code to adhere to React’s ideology and that would get really messy. This is where JSX helps a lot. The same code that you see above would otherwise have to be written as this (if not JSX):

ReactDOM.render(React.createElement(
  'h1',
  null,
  'Hello World!'
), document.getElementById('app'));

You can totally do this if you don’t want to work with JSX, in fact this is exactly what Babel (the browser.min.js) above produces when compiling our JSX code and executes that in the browser. But if you want to make your lives easier by writing XML (HTML) components directly in your React code that is much easier to understand for us humans, then stick to JSX which is really not much of a hassle.

Of course you can also put your JS in an external script and load that like this:

<script type="text/babel" src="main.js"></script>

Finally, let’s talk about why is this method not recommended ? I think you’d have already guessed that by now. So much compilation in the browser, is not a good idea for production (also gets really slow in development at times). Also the compiler itself is fairly large that can be completely avoided in production if you go the npm way.

Just an FYI that you can totally skip for now – I used Babel 5.x in the browser (if you noticed the code carefully). If you’d like to use Babel 6 (or above) right inside your browser (useful at times when making test cases on JSBin, JSFiddle, etc.), read this article on how to do it.

Setup With npm (Recommended)

We’ll install a couple of packages first, don’t get overwhelmed by the number of modules we install, I’ll explain what each and every package is for. Start off with an npm init in a new folder to setup a test react project.

$ npm init
$ npm install react react-dom babel-core babel-loader babelify babel-preset-react babel-preset-es2015
$ npm install browserify webpack webpack-dev-server babel-cli -g

Following are the modules that we installed:

  • react and react-dom – React libraries/packages basically. More on why two different packages.
  • babel-core – This is the core Babel compiler.
  • babel-loader – Webpack plugin for Babel.
  • babelify – Browserify transform module.
  • babel-preset-react and babel-preset-es2015 – Babel presets/plugins to transpile ES6 and React code.
  • browserify – It’s a module bundler, let’s you use Node.js style require('module') in the browser. I’d written about this tool a few years back.
  • webpack – Module bundler like Browserify with some extra features
  • webpack-dev-server – A small Node (Express) web server which serves a webpack bundle (bundled React app in our case) over HTTP. It also allows auto refreshing – so you make changes to your code and switch to your browser to see the reflected changes without explicitly reloading the browser tab.
  • babel-cli – Babel command line tools.

Note: Generally you’d use either browserify or webpack bundlers to setup your project. In this case I’ve downloaded both to show you different ways to setup our React app. We’ll use the babel packages to compile/transpile whereas browserify or webpack will help us bundle our modules with dependencies.

Let’s create two files and a directory:

$ touch index.html main.js
$ mkdir build

Put this code in your index.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>React App!</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="build/bundle.js"></script>
  </body>
</html>

In main.js put this:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello World!</h1>,
  document.getElementById('app')
);

Using Browserify

With browserify, using the babelify transform, we can compile our React code like this:

$ browserify -t [ babelify --presets [ es2015 react ] ] main.js -o build/bundle.js

That’s it! Open index.html in your browser and enjoy your shiny new React app. But there’s one problem now. Everytime we make a change to our main.js, we’ll have to manually compile it with browserify.

Not to worry! We can use Watchify. It is equivalent to browserify with a watch mode. Install and start using it like this:

# Install watchify
$ npm install watchify

# Replace browserify from the command above with ./node_modules/.bin/watchify
$ ./node_modules/.bin/watchify -t [ babelify --presets [ es2015 react ] ] main.js -o build/bundle.js

Using Webpack (Preferred)

Create a file called webpack.config.js that’ll contain webpack’s configuration. The configuration file is just a Node module.

module.exports = {
  // entry file
  entry: './main.js',
  output: {
    path: __dirname + '/build',
    publicPath: '/build/',
    filename: 'bundle.js'
  },
  // we will use webpack-dev-server
  devServer: {
    inline: true, // reload on the fly (auto refresh)
    port: 4567 // which port to run the server on
  },
  module: {
    // loaders are transformers basically
    loaders: [
      {
        // All files that end with `.js`
        test: /\.js$/,
        // Do not consider node_modules for webpack bundling
        exclude: /node_modules/,
        // use babel as the loader (transformer)
        loader: 'babel',
        // Passing queries/arguments to the loader
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  }
}

Now run the command $ webpack and it’ll create build/bundle.js at lightning speed. Want to watch for changes ? Sure – $ webpack --watch.

I prefer using webpack-dev-server because not only does it creates the bundle just like the webpack command, it also serves index.html automatically over the specified port (4567 in our case) and ensures auto-refresh in the browser (using websockets) as we make changes to our source files.

Note: It won’t actually create the bundle in your output path/directory though, it actually creates the bundle in memory and serves from there. Also the default port is 8080.

Read more on the webpack-dev-server command line configurations here that you can also use in the devServer block of webpack.config.js.

React Webpack Boilerplate

I’ve uploaded a very simple React, Babel, Webpack boilerplate on Github that you can use as a starter kit to kick off your React app. You can surely extend or modify it according to your needs as much as you want. It’s a highly minimal set of code and configuration.

Wrapping Up

Now that we have expertise in how to setup our React development environment, we’re ready to start learning the various concepts incorporated by the library and get comfy writing code in it. The next part will dive straight into the essentials of React.

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

2 thoughts on “Getting Started with React – Setting up the Development Environment”

  1. thank you for saving my life. it is the most straightforward minimal setup which i was looking for. just a quick note about index.html. the source path should be build/bundle.js not bundle/bundle.js. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

*