Build to UMD with [email protected]


Webpack is an excellent module bundler:

[It] takes modules with dependencies and generates static assets representing those modules. (Source.)

For JavaScript modules, webpack can be used to build a bundle for the browser and/or the server.

As a result, this means that you can generate a UMD build with webpack. This Universal Module Definition format allows JavaScript modules to be loaded via CommonJS, AMD, or script tag.

Let’s learn how to use webpack to output UMD.

Example

To get started, install [email protected] globally:

npm install -g [email protected]

Create an add module that returns the sum of two numbers:

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

Next, we’ll set up the webpack configuration:

// webpack.config.js
module.exports = {
  entry: './add.js',
  output: {
    filename: './dist/add.js',
    // export to AMD, CommonJS, or window
    libraryTarget: 'umd',
    // the name exported to window
    library: 'add'
  }
};

Build your bundle with the webpack command:

$ webpack
Hash: 81d114e86560c48d887b
Version: webpack 1.13.2
Time: 45ms
        Asset     Size  Chunks             Chunk Names
./dist/add.js  1.81 kB       0  [emitted]  main
   [0] ./add.js 55 bytes {0} [built]

You’ll see that the file is outputted to dist:

$ tree
.
├── add.js
├── dist
│   └── add.js
└── webpack.config.js

Now you can load your module via CommonJS, AMD, or a script tag.

CommonJS

$ node
> var add = require('./dist/add');
> add(1, 2);

AMD

<!-- amd.html -->
<html>
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
  <script>
    window.requirejs(['dist/add'], function(add) {
      console.log(add(1, 2));
    });
  </script>
</body>
</html>

Script Tag

<!-- script-tag.html -->
<html>
<body>
  <script src="./dist/add.js"></script>
  <script>
    console.log(window.add(1, 2));
  </script>
</body>
</html>