We have seen that modules in JavaScript allow you to organize and reuse 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 said, you should always prefer ESM modules now, because they are the JavaScript standard for creating modules.
However, CommonJS still exists (and will for some time) given 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
Using ES Modules
Modern browsers support ES modules directly via 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>
Using 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 browser-compatible format.
In Node.js
Using ES Modules
To use ESM, you need to add "type": "module" to 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
Using CommonJS
By default, Node.js uses CommonJS modules. You simply 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
