Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6437

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T06:31:07+00:00 2024-11-27T06:31:07+00:00

How to convert CommonJS to ESM

  • 60k

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
  • Update package.json
  • Other changes
  • Tools for migrating
  • What's next

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, - } 
Enter fullscreen mode Exit fullscreen mode

On the import side:

- const { addNumbers } = require("./add_numbers"); + import { addNumbers } from "./add_numbers.js");  console.log(addNumbers(2, 2)); 
Enter fullscreen mode Exit fullscreen mode

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")); 
Enter fullscreen mode Exit fullscreen mode

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",   // ... } 
Enter fullscreen mode Exit fullscreen mode

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"   } } 
Enter fullscreen mode Exit fullscreen mode

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"; 
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

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:

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. 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!

javascriptprogrammingtutorialwebdev
  • 0 0 Answers
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.