First off, make sure you have right tools. Node.js of course is the first thing you'll need (in order to
npm install anything).
Setup + Installs
Even if you're not creating a node-based project, node is useful when building and compiling. Create a package.json file with
npm init. All the defaults should work for a basic setup.
Next, install gulp.
sudo npm install gulp -g. This installs gulp globally so you can run
gulp from anywhere.
And you'll also need browserify. Just run
npm install browserify -g.
Create a gulpfile.js in your project. The first 3 things to put in your gulpfile are:
Before you can do anything, you need to install these three packages:
Next we're doing to create a basic gulp task called scripts.
So inside this task we want to do a few things:
- choose our source/main file
- run it through browserify
- transform it with reactify
- send it to our distribution folder
The great thing about gulp is that with the concept of piping you can add anything else to this workflow (minification, uglification, renaming, etc.).
Ok, on to the script:
Yep, it's pretty straightforward. Now, let's take a look at app.js.
There are a few things happening here. First, make sure you've gone and installed React (
npm install react). Then, we require our React component (more on that in a minute). Finally, we throw a pretty basic check for a
window, assume we're in the browser if it exists, and then render our component into the
Now let's explore the catalog React component:
This file is creating and exporting a very basic React component. I'm using jsx here, but you notice it's just Reactify doing the magic to transform. Tip: When it comes to server-side rendering of jsx, check out the
node-jsx npm module.
So, back to our Gulpfile. The last thing we have to do is add a watch task. The nice thing about Gulp is that it comes with watching functionality baked in.
This task simply watches any files ending in .js or .jsx, and then runs our
Finally we need to start everything off. Create a task (default works nicely) that runs our script task, and subsequently runs the watch task.
And that's about it! Run
gulp from the command line and watch everything come together. It's super simple to setup, and you can be creating React components in minutes. Throw the reference to the
dist/app.js in a test index.html file with an empty
#content div, and fire it up in the browser.