NPM scripts are way cooler than gulp and grunt


Lately I’ve been building apps in JavaScript and used process of build automation a lot. But for that I didn’t use tools like grunt (actually never used it) or gulp (used it) but with plain ol’ NPM. As you may know, you can define scripts in project’s package.json and then run them with “npm run <script-name>”. Another cool feature of this approach is that you don’t have to have various terminal commands (like browserify, uglifyjs,…) installed globally.

Here is an example: We’d like to minify our javascript code with uglifyjs. File is called main.js and located in project root.

  • First install the package: npm install uglifyjs
  • Then init a package.json: npm init -f
  • Open package.json and under scripts field add the following key/value pair:
    "min-js": "uglifyjs main.js -o main.min.js"
  • In terminal execute the following command: npm run min-js

Tip: When you find yourself typing a lot of command in single script, you can extract them in a bash file and call that file (you can help yourself with this package).

BONUS:

Building React-powered web application with browserify, ES2015 syntax and want to automatic rebuild when some file changes? And also with browser reload when rebuild is finished? Than use this command (change paths for entry file, output file and directory with static files accordingly):

watchify src/main.jsx -o public/main.js -dv -t [ babelify --presets [ es2015 react ] ] & live-server public --entry-file=index.html

Packages needed are watchify, live-server, babelify, babel-preset-react, babel-preset-es2015.

Now search for gulpfile or gruntfile that does the equivalent. Ha!

NPM scripts FTW!