Using npm scripts
While playing with
React,
Babel,
Browserify and
cssnext I decided to use npm
scripts instead of relying on a build
system. One of the benefits of using scripts, other than having fewer
dependencies in your project, is that the node_modules/.bin directory gets
added to your PATH. This
makes it easy to work with modules that you only use for development.
Here’s the scripts field from the
package.json
file:
{
"scripts": {
"start": "npm install && npm run setup && npm run dist",
"setup": "rm -rf dist && mkdir dist",
"dist": "npm run js && npm run css && npm run html",
"js": "browserify -t babelify -g uglifyify -e src/js/index.js > dist/index.js",
"css": "cssnext -c src/css/index.css > dist/index.css",
"html": "cp -r src/*.html dist/",
"serve": "http-server -p 5555 dist/",
"deploy": "git subtree push --prefix dist origin gh-pages"
}
}startanddistare “shortcuts” for the other scripts.setuptakes care of clearing and creating thedistfolder.jsruns JavaScript files through Browserify, which transforms and minifies them into a single file.cssruns the CSS file through cssnext and compresses the output.htmlcopies the HTML file.serveserves thedistfolder.deploydeploys thedistfolder to thegh-pagesbranch.
To run a script you run npm run <script>. start also has a shortcut, which
is npm start. If you can’t remember the name of a script you can list them all
by running npm run.
A note on Windows support
On my Windows machine I use Git Bash, which
gives me access to common UNIX tools. You can use modules like
rimraf,
mkdirp and
ncp as replacements for rm -rf, mkdir
-p and cp -r to make the scripts more portable.