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

推荐订阅源

T
Tailwind CSS Blog
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
V2EX - 技术
V2EX - 技术
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
F
Fortinet All Blogs
C
Cybersecurity and Infrastructure Security Agency CISA
A
Arctic Wolf
美团技术团队
Cloudbric
Cloudbric
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
S
Security Affairs
T
Tenable Blog
MyScale Blog
MyScale Blog
W
WeLiveSecurity
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
博客园_首页
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
月光博客
月光博客
宝玉的分享
宝玉的分享
博客园 - Franky
PCI Perspectives
PCI Perspectives
H
Hacker News: Front Page
D
Docker
博客园 - 司徒正美
L
LINUX DO - 最新话题
GbyAI
GbyAI
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
InfoQ
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
T
Threatpost
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
人人都是产品经理
人人都是产品经理
C
Check Point Blog
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
AI
AI
有赞技术团队
有赞技术团队
N
News | PayPal Newsroom
T
The Blog of Author Tim Ferriss
D
DataBreaches.Net
O
OpenAI News

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 Zero-config Debugging with Deno and OpenTelemetry | Deno Exploring Art with TypeScript, Jupyter, Polars, and Observable Plot | Deno Deno v Oracle Update 3: Fighting the JavaScript Trademark | Deno Build a custom RAG AI agent in TypeScript and Jupyter | Deno How to get deep traces in your Node.js backend with OTel and Deno | Deno toranoana.deno #20 登録受付中(2025年3月14日) | Deno Node just added TypeScript support. What does that mean for Deno? | Deno The Dino 🦕, the Llama 🦙, and the Whale 🐋 | Deno Publish a lint rule, get a prize | Deno Deno 2.2: OpenTelemetry, Lint Plugins, node:sqlite | Deno If you're not using npm specifiers, you're doing it wrong | Deno How Deno's documentation is evolving | Deno Oracle justified its JavaScript trademark with Node.js—now it wants that ignored | Deno Introducing the JSR open governance board | Deno Intro to Wasm in Deno | Deno Announcing OpenAI on JSR | Deno Deno in 2024 | Deno Goodbye WinterCG, welcome WinterTC | Deno Build a SolidJS app with Deno | Deno Run your Next.js SSR app on Deno Deploy | Deno Solve Advent of Code 2024 with Deno and Win Prizes! | Deno Deno v. Oracle: Canceling the JavaScript Trademark | Deno Deno 2.1: Wasm Imports and other enhancements | Deno Build a Typesafe API with tRPC and Deno | Deno Self-contained Executable Programs with Deno Compile | Deno Build a Database App with Drizzle ORM and Deno | Deno Introducing your new JavaScript package manager: Deno | Deno Announcing Growthbook on JSR | Deno Build an Astro site with Deno | Deno Announcing Deno 2 | Deno The Final Touches: What’s New In v2.0.0-rc.10 | Deno Announcing Stable V8 Bindings for Rust | Deno Deno 2.0 Release Candidate | Deno Secure, efficient private npm registries with Cloudsmith and Deno | Deno Painting the Plane as We Fly It: Designing JSR | Deno Introducing Web Cache API support on Deno Deploy | Deno Deno 1.46: The Last 1.x Release | Deno Protect your cloud spend with new Deno Deploy spend limits | Deno What we got wrong about HTTP imports | Deno Benchmarking AWS Lambda Cold Starts Across JavaScript Runtimes | Deno Announcing Supabase on JSR | Deno Deno 1.45: Workspace and Monorepo Support | Deno Introducing KV Backup for Deno Subhosting | Deno A Gentle Intro to TypeScript | Deno Announcing Hono on JSR | Deno How We Made the Deno Language Server Ten Times Faster | Deno How the Guardian uses Deno to audit accessibility and performance across their 2.7 million articles | Deno Introducing More Flexible Domain Association for Deno Subhosting | Deno The stabilization process of the Standard Library has begun | Deno Deno 1.44: Private npm registries, improved Node.js compat, and performance boosts | Deno How we built a secure, performant, multi-tenant cloud platform to run untrusted code | Deno The Deno Standard Library is now available on JSR | Deno How to document your JavaScript package | Deno Your Low Code Solution Needs an Escape Hatch | Deno Deno 1.43: Improved Language Server performance | Deno How Slack used Deno to save months of engineering effort in launching their new platform | Deno JSR Is Not Another Package Manager | Deno Announcing the Hookdeck SDK on JSR | Deno Announcing the Neon Serverless Driver on JSR | Deno An intro to TSConfig for JavaScript Developers | Deno How we built JSR | Deno How Netlify used Deno Subhosting to build a successful edge functions product | Deno Introducing Simpler Project Creation in Deno Deploy | Deno Deno 1.42: Better dependency management with JSR | Deno Introducing deployctl, the command line interface for Deno Deploy | Deno Introducing JSR - the JavaScript Registry | Deno How to add Monaco to a Next.js app and securely run untrusted user code | Deno Survey Results and Roadmap | Deno Deno 1.41: smaller deno compile binaries | Deno Webhooks suck, but here are alternatives | 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.