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 -->
<html>
<body>
  <!-- will this work? -->
  <script src="main.js"></script>
</body>
</html>

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.

Install

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 -->
<html>
<body>
  <!-- open your console to see the logs -->
  <script src="bundle.js"></script>
</body>
</html>

Additionally, webpack has some useful plugins.

Watch

Enable the watch option for automatic recompilation on file change:

$ webpack main.js bundle.js -w

Debug

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

$ webpack main.js bundle.js -d

Production

Enable the production option to minify or compress your bundle:

$ webpack main.js bundle.js -p

Configuration

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