How to Use NPM as Development tool for React


For last couple of years I have been using Grunt as my default build tool. Later I got interested in Gulp, it was solving many problems of Grunt. But somehow they all looked bloated to me. Had to install a lot of packages to perform even simple tasks. Thanks to @keithamus whose wonderfull post demostrated how we can use npm as a build tool.

In this post I would be guiding you how I used npm for the development of react applications. Specifically I had following objectives:

  • Compile JSX
  • Compile LESS
  • livereload when there is a change in js or less file

Install required packages

To keep things simple I am using plain javascript files, without any requireJS or browerify. For this I install following packages.

  • envify
  • less
  • live-reload
  • nodemon
  • react-tools
  • watchify
  • parallelshell

You can simply install these packages with shooting npm install <package_name> --save-dev. This will save these packages as development dependencies in package.json file. Before doing so you must initialize you package.json file with npm init.

Scripts are as follows:

"scripts": {
  "livereload": "live-reload --port 9091 dist/",
  "watch-css": "nodemon -w css --ext less --exec 'lessc -s css/main.less dist/bundle.css'",
  "watch-js": "watchify -o dist/bundle.js -v -d .",
  "watch-jsx": "jsx --watch js/ dist/js/",
  "start": "parallelshell 'npm run livereload' 'npm run watch-css' 'npm run watch-jsx'"

Now I just have to fire npm start and it watches all my js/jsx in js/ directory and put compiled version in dist/js/. Compiles css/main.less to dist/bundle.css. My main.less have references to other css/less files. It also runs a livereload server to watch any changes in less/js files.

So you can see with these simple npm scripts we can easily automate development tasks, without using bloat offered by Grunt/Gulp.

Leave a Reply