We have seen that modules in JavaScript allow organizing and reusing code in projects, and that there are two main module systems:
- ES Modules (ESM), part of the ECMAScript standard
- CommonJS (CSM), initially created for Node.js
As we mentioned, we should always prefer ESM modules, because they are the JavaScript standard for creating modules.
However, CommonJS still exists (and will for a while) due to the popularity it gained thanks to Node.js.
Now let’s see how to use each of them, both in a browser and in a runtime like Node.js.
Platform | ES Modules (ESM) | CommonJS |
---|---|---|
Browser | 🟢 Natively supported | 🔴 Not supported |
Node.js | 🟡 Supported | 🟢 Natively supported |
In the Browser
Use ES Modules
Modern browsers support ES modules directly through the type="module"
attribute in the <script>
tag.
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Modules in the Browser</title>
</head>
<body>
<script type="module">
import { add } from './math.js';
console.log(add(2, 3)); // 5
</script>
</body>
</html>
Use CommonJS
Browsers do not natively support CommonJS. To use CommonJS modules, you need tools like Browserify or Webpack, (and many many others) that convert the code into a format compatible with the browser.
In Node.js
Use ES Modules
To use ESM, you need to add "type": "module"
in your package.json
file.
{
"type": "module"
}
With this configuration, you can use import
and export
in your files.
// file: math.js
export const add = (a, b) => a + b;
// file: app.js
import { add } from './math.js';
console.log(add(4, 6)); // 10
Use CommonJS
By default, Node.js uses CommonJS modules. You just need to use the require
and module.exports
syntax.
// file: math.js
const add = (a, b) => a + b;
module.exports = { add };
// file: app.js
const { add } = require('./math');
console.log(add(4, 6)); // 10