Getting started with [email protected]

Let’s say you have an add module that returns the sum of two numbers:

// add.js
module.exports = function add(a, b) {
  return a + b;

And main.js uses add:

// main.js
var add = require('./add');
console.log('2 + 2 =', add(2, 2));
console.log('1 + 1 =', add(1, 1));

We know running main.js with node on the command-line works:

$ node main.js
2 + 2 = 4
1 + 1 = 2

But what if we want to load main.js in the browser?

<!-- index.html -->
  <!-- will this work? -->
  <script src="main.js"></script>

This obviously doesn’t work. The browser doesn’t understand CommonJS so it’s unable to load the module.

To make this work, we’ll need to perform module bundling.

Webpack is a popular module bundler that takes CommonJS modules and concatenates them into a single JavaScript file. There are loaders and plugins that can enhance the compilation, but that’s beyond the scope of this tutorial.


To get started, install webpack globally:

$ npm install -g [email protected]

The quickest way to build your bundle without having to create a configuration file is with the CLI command:

$ webpack main.js bundle.js
# webpack <entry> <output>

Update the script tag to the bundle path and it should now work:

<!-- index.html -->
  <!-- open your console to see the logs -->
  <script src="bundle.js"></script>

Additionally, webpack has some useful plugins.


Enable the watch option for automatic recompilation on file change:

$ webpack main.js bundle.js -w


Enable the debug option to create source maps to see where errors occur:

$ webpack main.js bundle.js -d


Enable the production option to minify or compress your bundle:

$ webpack main.js bundle.js -p


Creating a webpack.config.js is the alternative to passing options to the CLI command:

// webpack.config.js
module.exports = {
  entry: './main.js',
  output: 'bundle.js'

Now you can run webpack without any arguments:

$ webpack