惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
aimingoo的专栏
aimingoo的专栏
博客园 - 叶小钗
H
Help Net Security
Microsoft Security Blog
Microsoft Security Blog
The Cloudflare Blog
S
SegmentFault 最新的问题
小众软件
小众软件
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
量子位
H
Hackread – Cybersecurity News, Data Breaches, AI and More
V
V2EX
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
J
Java Code Geeks
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
Blog — PlanetScale
Blog — PlanetScale
Last Week in AI
Last Week in AI

Deno

Deno 2.8 | Deno Claw Patrol: an open-source security firewall for agents | Deno Fresh 2.3: Zero JS by default, View Transitions, and Temporal support | Deno Deno 2.7: Temporal API, Windows ARM, and npm overrides | Deno Build a dinosaur runner game with Deno, pt. 6 | Deno Build a dinosaur runner game with Deno, pt. 5 | Deno Deno Deploy is Generally Available | Deno Introducing Deno Sandbox | Deno Build a dinosaur runner game with Deno, pt. 4 | Deno Build a dinosaur runner game with Deno, pt. 3 | Deno Build a dinosaur runner game with Deno, pt. 2 | Deno React / Next.js Denial-of-Service Vulnerability: Deno Deploy users protected | Deno Deno 2.6: dx is the new npx | Deno Build a dinosaur runner game with Deno, pt. 1 | Deno React Server Functions / Next.js Vulnerability: Deno Deploy users protected | Deno My highlights from the new Deno Deploy | Deno Deno's Other Open Source Projects | Deno How Deno protects against npm exploits | Deno Help Us Raise $200k to Free JavaScript from Oracle | Deno Deno 2.5: Permissions in the config file | Deno Fresh 2.0 Graduates to Beta, Adds Vite Support | Deno Deno 2.4: deno bundle is back | Deno JavaScript™ Trademark Update | Deno What's coming to JavaScript | Deno A brief history of JavaScript | Deno Reports of Deno's Demise Have Been Greatly Exaggerated | Deno An Update on Fresh | Deno How Plaid migrated 100 services to a new database platform 5x faster with Deno | Deno Deno 2.3: Improved deno compile, local npm packages, and more | Deno Add JSR packages with pnpm and Yarn | Deno
How to convert CommonJS to ESM | Deno
Andy Jiang · 2024-10-16 · via Deno

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.

  • Module imports and exports
  • Update package.json
  • Other changes
  • Tools for migrating
  • What’s next

Want to write modern JavaScript and TypeScript without tedious config or boilerplate?

Check out Deno, a “batteries-included”, secure-by-default all-in-one toolchain for JavaScript development with native TypeScript and web standard API support.

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:

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:


const __dirname = import.meta.dirname;
const __filename = import.meta.filename;


const __dirname = new URL(".", import.meta.url).pathname;

import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);

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:

VSCode offers a quick fix to converting CommonJS requires to ESM imports.

You’ll notice that VSCode can swap out the proper keywords for importing and exporting, but the specifiers are missing filename extensions. 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 is the CLI tool ts2esm, which converts CJS to ESM, and includes step-by-step instructions and even a nifty video walkthrough.

There are ones like cjs2esm and cjstoesm, as well as the Babel plugin babel-plugin-transform-commonjs, though these tools are not actively maintained 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. In fact, JSR, our open source modern JavaScript registry explicitly forbids modules using CommonJS. We urge everyone to do their part in leveling up the JavaScript ecosystem.

🚨️ Try Deno 2 today. 🚨️

Deno offers backwards compatibilty with Node/npm, built-in package management, all-in-one zero-config toolchain, native TypeScript support, and more.