Webpack: Build UMD bundle


This article goes over how to build a UMD (Universal Module Definition) JavaScript bundle with webpack.

The UMD format allows JavaScript modules to be imported using:

Prerequisites

Install webpack and webpack-cli:

$ npm install webpack webpack-cli --save-dev

Your package.json will look like:

{
  "devDependencies": {
    "webpack": "^5.36.2",
    "webpack-cli": "^4.6.0"
  }
}

Module

Create module:

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

Add webpack configuration:

// webpack.config.js
module.exports = {
  entry: './src/add.js',
  output: {
    filename: 'add.js',
    library: {
      type: 'umd',
      name: 'add',
    },
    // prevent error: `Uncaught ReferenceError: self is not define`
    globalObject: 'this',
  },
};

Run webpack to build your bundle:

$ npx webpack
asset add.js 399 bytes [compared for emit] [minimized] (name: main)
./src/add.js 57 bytes [built] [code generated]

The output file will be in dist:

$ tree -I node_modules
.
├── dist
│   └── add.js
├── package.json
└── src
    └── index.js

2 directories, 3 files

Import

CommonJS

Require module with CommonJS:

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

AMD

Load module with AMD:

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

Script

Load module with script tag:

<!-- script.html -->
<h1></h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script>
  window.requirejs(['dist/add'], function (add) {
    document.querySelector('h1').innerText = add(1, 2);
  });
</script>

Demo

Repl.it:



Please support this site and join our Discord!