How to convert CommonJS to ESM
Jo Franchetti
Posted on October 22, 2024
ECMAScript modules (”ESM”) are the official, modern way of writing and sharing JavaScript — it’s supported in many environments (e.g. browsers, the edge, and modern runtimes like Deno, and offers a better development experience (e.g. async loading and being able to export without globals). While CommonJS was the standard for many years, supporting CommonJS today is hurting the JavaScript community.
All new JavaScript should be written in ESM for future proofing. However, there are many cases where a legacy code base needs to be modernized for compatibility reasons with newer packages. In this blog post, we’ll show you how to migrate the syntax of a legacy CommonJS project to one that supports ESM and tools to help smooth out that process.
In this document
Module imports and exports
Here’s how you can update import and export syntax from CommonJS to ESM.
On the export side:
- function addNumbers(num1, num2) {
+ export function addNumbers(num1, num2) {
return num1 + num2;
};
- module.exports = {
- addNumbers,
- }
On the import side:
- const { addNumbers } = require("./add_numbers");
+ import { addNumbers } from "./add_numbers.js");
console.log(addNumbers(2, 2));
Note that in ESM, the file extension must be included in the module path. Fully specified imports reduce ambiguity by ensuring the correct file is always imported by the module resolution process. Plus, it aligns with how browsers handle module imports, making it easier to write isomorphic code that’s predictable and maintainable.
What about conditional imports? If you are using Node.js v14.8 or later (or Deno), then you’ll have access to top-level await, which you can use to make import
synchronous:
- const module = boolean ? require("module1") : require("module2");
+ const module = await (boolean ? import("module1") : import("module2"));
Update package.json
If you’re using package.json
, you’ll need to make a few adjustments to support ESM:
{
"name": "my-project",
+ "type": "module",
- "main": "index.js",
+ "exports": "./index.js",
// ...
}
Note the leading "./"
in ESM is necessary as every reference has to use the full pathname, including directory and file extension.
Also, both "main"
and "exports"
define entry points for a project. However, "exports"
is a modern alternative to "main"
in that it gives authors the ability to clearly define the public interface for their package by allowing multiple entry points, supporting conditional entry resolution between environments, and preventing other entry points outside of those defined in "exports"
.
{
"name": "my-project",
"type": "module",
"exports": {
".": "./index.js",
"./other": "./other.js"
}
}
Finally, another way to tell Node to run the file in ESM is to use the .mjs
file extension. This is great if you want to update a single file to ESM. But if your goal is to convert your entire code base, it’s easier to update the type
in your package.json
.
Other changes
Since JavaScript inside an ESM will automatically run in strict mode, you can remove all instances of "use strict";
from your code base:
- "use strict";
CommonJS also supported a handful of built-in globals that do not exist in ESM, such as __dirname
and __filename
. One simple way to get around that is to use a quick shim to populate those values:
// Node 20.11.0+, Deno 1.40.0+
const __dirname = import.meta.dirname;
const __filename = import.meta.filename;
// Previously
const __dirname = new URL(".", import.meta.url).pathname;
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
Tools for migrating
While the above touches upon the changes necessary to convert a CommonJS code base to an ESM one, there are a few tools to help with that transition.
With VSCode, you can quickly convert all import and export statements from CommonJS to ESM. Simply hover over the require
keyword, hit “quick fix”, and all of those statements in that file will be updated to ESM:
You’ll notice that VSCode can swap out the proper keywords for importing and exporting, but the specifiers are missing filename extensions. If you have Deno installed, you can quickly add them by running deno lint --fix
. Deno’s linter comes with a no-sloppy-imports
rule that will show a linting error when an import path doesn’t contain the file extension.
For a more end-to-end approach to converting CommonJS to ESM, there are a few transpilation options. There are npm packages cjs2esm and cjstoesm, as well as the Babel plugin babel-plugin-transform-commonjs. However, these tools may not be actively maintained and are not feature complete, so keep that in mind when evaluating them.
What’s next
ESM is the standard JavaScript way to share code and all new JavaScript should support it. Choosing to support CommonJS today can be extremely painful for module authors and developers who don’t want to troubleshoot legacy compatibility issues. JSR - the open source, modern JavaScript registry, explicitly forbids modules using CommonJS. Everyone can do their part in levelling up the JavaScript ecosystem!
Posted on October 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 20, 2024