Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to browserify, compile ES6 and minify NodeJS application

I am trying to get to grips with browserify and ES6 simultaneously. I have the following basic Node files:

main.js

var foo = require('./foo.js');
var x = foo.math(200);
console.log(x);

foo.js

exports.math = (n)=>{ 
  return n * 111;
};

Now I want to do the following:

  • Browserify this into a file bundle.js so I can include it as a script in my website
  • Compile the JS using babel to make the ES6 readable by all browsers
  • Minify bundle.js to improve load times in the browser

I have browserify installed globally and I run that with this command: browserify main.js > bundle.js

Works great. But should I be running babel first? How do I complete my 3 step process and in what order (of course minification will have to happen last)? Should I be doing this all with grunt?

like image 625
CaribouCode Avatar asked Nov 07 '15 12:11

CaribouCode


People also ask

How do I use Browserify require?

Bundle up your first module With Browserify you can write code that uses require in the same way that you would use it in Node. Browserify parses the AST for require() calls to traverse the entire dependency graph of your project. Drop a single <script> tag into your html and you're done!

How do I use Browserify bundles?

Use a node-style require() to organize your browser code and load modules installed by npm. browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single <script> tag.

What are two Browserify functions?

Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code.

What is Browserify in NPM?

Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.


2 Answers

It shouldn't be necessary anymore to use a task runner. However, use a neat plugin like babelify from command line as described in its README.md here.

npm install --save-dev browserify babelify babel-preset-es2015

browserify script.js -o bundle.js \
    -t [ babelify --presets es2015 ] 

And add other transforms as needed from here or any where else, e.g. uglify.

like image 59
eljefedelrodeodeljefe Avatar answered Sep 28 '22 13:09

eljefedelrodeodeljefe


For es6 use uglify-es, it supports ES6.

npm install uglify-es -g

like image 38
Sudhanshu Gaur Avatar answered Sep 28 '22 13:09

Sudhanshu Gaur