Getting React Running with Express (Basics for Beginners)

Introduction

You’ve heard of React. It’s hot, hot, ouch-where-is-the-aloe-vera hot right now. You’ve probably checked out the React docs, too. “Hey, you can make re-useable UI components,” you thought. “That sounds neat. And they make it look really easy!”

Then you thought, “Okay, I want to use React in my Node/Express project! Let’s go!”

If you’re like me, here is where you hit a wall. React’s “Getting Started” page offers these ‘simple’ instructions:

To install React DOM and build your bundle with browserify:
$ npm install --save react react-dom babelify babel-preset-react
$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js
To install React DOM and build your bundle with webpack:
$ npm install --save react react-dom babel-preset-react
$ webpack

Yes, you can copy and paste these commands into your terminal and hope for the best, but the docs don’t exactly hold your hand and explain what is going on here. I was baffled. What do all these nonsense words have to do with React? After digging and putzing and fiddling and tinkering, the mysteries have been revealed to me. I shall now share these dark secrets with you — the secrets of Gulp and Browserify!

The Nitty Gritty

This tutorial/explanation assumes you are fairly familiar with npm and you know how set up a simple Express server. Thus, hopefully you know what a package.json file is for. Here are all the development dependencies we are going to need as shown in our package.json:

Check out those dependencies. Even more nonsense words than you expected? Do not fret. I’m going to break down why we need each of these things and where they will physically fit in to your project.

‘babel-preset-react’ and ‘babelify’: If you’ve skimmed the React docs, you know that React components take advantage of an XML-like syntax called JSX. For example, your component’s return function might look like this:

var MyComponent = React.createClass({
render: function() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.article}</p>
</div>;
);
}
});

Hey, that kind of looks like HTML! But it isn’t… this is JSX, and though you don’t have to use it with React, most tutorials I’ve seen do. The problem is, the browser doesn’t know how to handle JSX (“Hmm, okay, yeah, there’s some JavaScript, yep, fine, WHOAAA is that HTML why is that in here?!!”). That’s where Babel comes in. All Babel does is translate the JSX into plain JavaScript so the browser can understand it. Babel is sometimes called a JavaScript compiler, a transpiler, or a transformer (all of which mean the same thing here). ‘babel-preset-react’ is a dependency because Babel can compile a few different flavors of JavaScript; in this case, we want the React presets. But why is our other dependency called ‘babelify’? Is that different from Babel? Yes it is, but just a little. More on that next.

‘browserify’: Okay, so now we can use JSX syntax with our React components. But wait, how does this Babel compiler thing work? Like, when I write my component and it translates it to regular ol’ JavaScript, where does that happen? Where does that JavaScript go? A very important question, and I’m glad you asked. Babel needs a place to put the JavaScript that it creates, and that is where Browserify comes in. In a nutshell, Browserify enables you to compartmentalize your code into bite-sized modules and then serve them up to your app in a nice concise bundle. So, rather than having several <script> tags for all of your js files, you would simply include one: <script src=”scripts/bundle.js”>

Browserify is pretty neat. Considering that it’s all about modular code, it makes sense that most of its functionality doesn’t come out-of-the-box, but rather exists in numerous modules and plugins. Babelify is a Browserify plugin that allows you to compile your files during the process of creating your bundle.js (you can name the bundle whatever you like, FYI). So, the funky JSX will be passed in to Browserify, compiled with Babel (Babelify), and then bundled up for use.

‘gulp’: Wait, what if I make a change to my React component? Do I have to compile and bundle my stuff every single time?? Well, yes, you would, if it weren’t for Gulp. Gulp allows you to write ‘tasks’ that will perform these compiling and bundling operations automatically. Gulp is installed globally with npm:

sudo npm install -g gulp

Then a gulpfile.js in your project root directory will define your tasks.

OMG, we’re only halfway through the dependencies, and we haven’t written ANY React!! Get on with it! Okay, calm down. We’re actually almost through; the rest of the dependencies are mostly little extras. Actually, every dev dependency we’re using is going to be used in this gulpfile, and then you can put them in the back of your mind and start writing React. Here, I’ll show you some code — will that make you happy? This is my gulpfile.js. It might seem incomprehensible at first, but I’ll break it down.

This leaves us with two Gulp tasks defined. The first, “gulp build”, will grab the root javascript file of your app, recursively find any other files it needs to include based on what modules it requires, run them through the Babel compiler, bundle them together, and output them to ‘/src/dist/scripts/bundle.js’. This wasn’t a stellar explanation of how Gulp works, so I encourage you to check out this video by Cary Landholt— it’s a bit old (in developer time), but he makes things really clear.

‘gulp-util’ is a Gulp package that allows us to log any errors that may occur during the tasks. See lines 33 and 44 above.

‘vinyl-source-stream’: We include this because it allows Browserify and Gulp to play nice together. On line 36 we use it to take the results of Browserify’s bundle and hand them off to Gulp in a way that Gulp understands (note that ‘vinyl-source-stream’ is loaded into the variable ‘source’). To be honest, the exact inner workings of this are over my head at the moment. If you want to know more, Google it!

‘watchify’: I have some bad news. I have betrayed you. This isn’t the “bare-bones” example I professed it to be. We could run React without watchify. But I think you’ll be happy you included it in your app. Watchify is another Browserify plugin that was developed to speed up re-bundling of your files during development. When we run the default Gulp task (simply ‘gulp’), Gulp will build everything just like the first command, but this time it will continue watching for any changes you make to your files. As soon as you make a change, it will automatically re-bundle your stuff (Gulp does have built in ‘watch’ functionality, but it re-bundles everything if a change occurs, which can take multiple minutes. Watchify is much much faster because it caches the bundle and only changes what needs to be changed).

Wrapping up

Here is my repo that shows how everything fits together. One caveat: please don’t take my file structure as the be-all end-all convention. There are tons of conventions out there, and as a NOOB myself I’m still figuring out what makes sense. To get set up, run the following commands from the root directory:

Install dependencies:

npm install

Run Gulp to create the bundle and watch for changes:

gulp

In a new tab, start the server:

npm start

Then you can see the SUPER IMPRESSIVE results by visiting localhost:3000 in your browser. This is the most useless React component of all time. But hey, we’re running React in our Express app, and that’s cool. Notice how Browserify knows to include the App.js component, even though it’s in a completely different directory from the main.js file that we pass into our Gulp task.

I hope this helped demystify the process of including React in an Express project. There is definitely a lot I didn’t explicitly explain here, but be sure to poke around the example repo (I would definitely check out the index.html and index.js files for additional clarity). Of course, Google is your friend as well.

Thanks for reading! This is my first blog post ever, so please leave feedback if you have any, and I’ll try my best to answer any questions you have.

Further Notes

Remember the React ‘Getting Started’ page? So now we have some understanding of what is going on in that first command (It will bundle up whatever is in the main.js file, but we would have to run that command every time we made a change. We added Gulp so we don’t have to.) But what about the second option, using webpack?

The tools described above are just one of many varied ways to get React working. The main source of difficulty for me personally was the sheer number of options one has. Here are some brief snippets about other options, and why I chose the route I did:

Webpack is another tool for bundling your modules. From what I read, more developers actually seem to use Webpack for their React projects, but it is generally agreed that Browserify is a simpler entry point for beginners. This article by Naman Goel goes into more detail.

Reactify is a Browserify plugin that you may see around. It serves the same purpose as Babelify, compiling JSX code into JavaScript for the browser to understand. I chose Babelify because it was updated more recently, and the React docs also explicitly refer to it.

Grunt is a counterpart to Gulp, just as Webpack is a counterpart to Browserify (Any devs out there who know their stuff might call me a fool for making the comparison. Please do so below in the comments and drop some learnin’ on me). Grunt can also be used to run repetitive build tasks. I chose Gulp because the general consensus seems to be that it’s easier to pick up. This article by Preslav Rachev goes into more detail.

Lastly, you may have come across someone’s “React boilerplate” repo or other quick-start package (or maybe you came across dozens of them). I cloned a couple of them, but mainly for the purposes of figuring out the nuts and bolts. I’m not against using these, but I feel gaining some understanding of what is going on under the hood is really valuable and can prevent frustration down the road (I’m really happy I learned about Browserify and Gulp because they obviously have use beyond React). So please, don’t think of my above repo as a boilerplate, but rather as an example to poke around with.