22

Some packages we install from npm support both commonjs and es modules,

These packages can be imported as follows:

import express from 'express'
// or
const express = require('express')

I have created a package which I already published to npm using es modules.

and I since my another project which I'm working on is built with commonjs, I realized that I can not require it using the following syntax:

const stackPlayer = require('stack-player')

How can I support the two module systems in my package stack-player so that everyone around the world can use it?

  • Is there another method other than converting all of my project to es modules (which would be too complex since the project is 1 year old and is big enough to refuse the idea). ?
11
  • Have you looked at the source of express how they did it? You can just use exports = module.exports = require('./stack-player'); Commented Feb 2, 2023 at 10:00
  • 1
    P.S: Your package works with both import and require. I've tested it. Commented Feb 2, 2023 at 12:09
  • 1
    That is something else and it is a different thing. I mean I've installed your package, and I've tested and it was fine. So if you want to use ESM syntaxes, that would be a different thing. You bring up an example from Express, and Express doesn't use ESM syntaxes in their current code. Commented Feb 2, 2023 at 12:41
  • 2
    @MostafaFakhraei, I want to develop my package in es6 modules, and I want anyone to install it, and require() it or import it. Of course, it worked with you because it's written in commonjs, I want to re-write it using es6 modules. 😁
    – Normal
    Commented Feb 2, 2023 at 12:52
  • 1
    @DanielKaplan no harm no foul. I took a closer look at the post topic and realized what was going on. Anyhow, I've posted an answer that you might find helpful. Happy new year. BTW, I miss the "gourmet ghetto" and all the other fabulous food in your area.
    – morganney
    Commented Jan 10 at 20:53

3 Answers 3

32
+50

There are two main scenarios:

1. Your package is written using CommonJS (CJS) module loading

This means your package uses require() to load dependencies. For this kind of package no special work is needed to support loading the package in both ES and CJS modules. ES modules are able to load CJS modules via the import statement, with the minor caveat that only default-import syntax is supported. And CJS modules are able to load other CJS modules via the require() function. So both ES modules and CJS modules are able to load CJS modules.

2. Your package is written using ES module loading

This means your package uses import to load dependencies. But don't be fooled - sometimes, especially when using TypeScript, you may be writing import in your code, but it's getting compiled to require() behind the scenes.

Unfortunately, CommonJS modules do not support loading ES modules except (in Node.js) by using the import() function (which is a bit painful and not a great solution).

In order to support CommonJS in this case, your best bet is to transpile your package into a CommonJS module, and ship both CommonJS and ESM versions of your package.

I do this in a number of my own packages mostly by using Rollup, which makes it relatively easy.

The basic concept is this:

  1. Write your package as an ES module.
  2. Install rollup: npm i -D rollup
  3. Run npx rollup index.js --file index.cjs --format cjs to convert your code into a CJS module.
  4. Export both from your package.json:
{
  "name": "my-package",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "exports": {
    "import": "./index.js",
    "require": "./index.cjs"
  }
}

This way, the CJS module loader knows to load your index.cjs file, while the ESM loader knows to load your index.js file, and both are happy.

5
  • the CJS module loader knows to load your index.cjs file, while the ESM loader knows to load your index.js file, and both are happy. So you are saying if import the dependency, some behind the scenes magic is choosing one file instead of the other, and if I use a require, different magic picks the cjs file? Commented Jan 10 at 20:20
  • 1
    Yes @DanielKaplan when you use require and when you use import you're running very different code that loads modules in different ways. The CJS module loader will prefer using the require field in the module's package.json, while the ES module loader will prefer using the import field. Keep in mind however the caveat regarding TypeScript, where it's common to write import in your TS code, but you have TS configured to compile that to require instead. In that case, even though you're writing import, require is being used and the CJS module loader is being invoked.
    – Aurast
    Commented Jan 11 at 14:05
  • I heard about something called UMD, so is UMD another solution or what?
    – Normal
    Commented Jun 6 at 5:14
  • @Normal Sort of. UMD isn't really a first-class type of module, it's more like a coding convention to create code that can work in several different environments. In Node.js, a UMD module would be loaded as a CJS module by the CJS module loader. A UMD module contains code that sees "oh look, I have a module.exports object available to me, I must be getting loaded as a CJS module" and it attaches its exports to module.exports in Node.js. In other environments too (like browser and AMD modules) it will detect how it's being loaded and change behavior accordingly.
    – Aurast
    Commented Jun 7 at 11:11
  • Thanks for that!! I've been wrestling with how best to handle the esm / cjs issue for ages. Everything I found seemed like a poor compromise. Commented Aug 29 at 5:57
9

require() Usage

require() can, by default, only be used in CommonJS Modules. The built in method to import ECMAScript modules into CommonJS is using import(pathToFile).then(module => { }).

Support for require()

If you want to support require() for your package, you must provide a CommonJS module.

Here's a functioning example that demonstrates when and how to utilize require() or import(). There are some small differences how import() of a CommonJS module works compared to a ECMAScript Module. Especially that only the default property on the module object is available, when import() is used on a CommonJS file that exported something with module.exports.

index.js which imports different module types (from the demo above):
(In case the stackblitz demo will be deleted:)

// executed as CommonJS module
console.time('');
import('./lib/example.cjs').then(({ default: example }) => {
  console.timeLog('', 'import cjs', example() == 'Foo'); // true
});
import('./lib/index.mjs').then(({ example }) => {
  console.timeLog('', 'import mjs', example() == 'Foo'); // true
});
try {
  const example = require('./lib/example.cjs');
  console.timeLog('', 'require cjs', example() == 'Foo'); // true
} catch (e) {
  console.timeLog('', 'require cjs', '\n' + e.message);
}
try {
  const example = require('./lib/index.mjs');
  console.timeLog('', 'require mjs', example() == 'Foo');
} catch (e) {
  console.timeLog('', 'require mjs', '\n' + e.message); // Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/lib/index.mjs not supported.
}

lib/example.cjs

module.exports = function example() {
  return 'Foo';
};

lib/index.mjs

import example from './example.cjs';
export { example };
export default example;

Conditional Export for Packages

A conditional export can be supplied for packages to support require(), for example in a case where the CommonJS require() is no longer supported by your package. Refer to this link for more information.

The "exports" field allows defining the entry points of a package when imported by name loaded either via a node_modules lookup or a self-reference to its own name. It is supported in Node.js 12+ as an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules.

package.json (example from the nodejs docs)

{
  "exports": {
    "import": "./index-import.js",
    "require": "./index-require.cjs"
  },
  "type": "module"
}

If so, you have to provide two scripts: one for the CommonJS ("require": "filename") and one for the ECMAScript module ("import": "filename").

While index-require.js must provide the script via exports = ... or module.exports = ..., index-import.js must provide the script with export default.

Keyword Usage

You can only use specific keywords depending on the files module type.

CommonJS Modules
  • module.exports is used to define the values that a module exports and makes available for other modules to require. It can be set to any value, including an object, function, or a simple data type like a string or number.
  • exports, module
    • If you use them inside an ECMAScript module you'll get an undefined Error.
  • require()
    • require() inside ECMAScript modules is possible, but you have to use a workaround as mentioned in this answer or take a look at the docs for module.createRequire(fileName):

      import { createRequire } from 'node:module';
      const require = createRequire(import.meta.url);
      
      // sibling-module.js is a CommonJS module.
      const siblingModule = require('./sibling-module');
      
    • If you call require() from within a CommonJS on an ECMAScript module, it throws a not supported Error:

      Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/script.mjs not supported.
      

      With a more detailed error message depending on the situation:

      Instead change the require of script.mjs in /path/to/app.js to a dynamic import() which is available in all CommonJS modules.

      Or:

      /path/to/script.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.

      Instead rename /path/to/script.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /path/to/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

ECMAScript Moduls (ESM)
  • export default is used to export a single value as the default export of a module. This allows for a more concise way to import values, as the import statement can omit the curly braces when importing the default export.
  • Named exports, on the other hand, allow multiple values to be exported from a module. Named exports use the export keyword followed by an identifier and a value. (export const foo = "bar")
  • import ... from ...
    • It can handle CommonJS files and interprets them as if you would've used require().

      Example based on express:

      import express, { Route, Router } from 'express'; // EJS
      // is similar to:
      var express = require("express"), { Route, Router } = express; // CJS
      

Both CommonJS and ECMAScript modules support the import() function, but the returned object can have more properties on ESM files.

Summary:

CJS modules don't need to be converted to ESM, as they can be imported into ESM using the import ... from ... syntax without any modifications to the CJS module. However, it's advisable to write new modules using ECMAScript Module syntax, as it is the standard for both web and server-side applications and enables seamless use of the same code on both sides the browser/client-side and node/server-side.

Additionally, I find this article on CommonJS vs. ES modules in Node.js from logrocket.com to be very informative. It delves into the pros and cons of ECMAScript compared to CommonJS in more depth.

Links:
2

When I'm publishing an npm package with TypeScript, for either node.js or the browser, I use @knighted/duel (I am also the author if that matters to you).

It is as easy as creating a tsconfig.json and package.json with a defined type and then defining an npm run script to create a dual build.

tsconfig.json

{
  "compilerOptions": {
    "declaration": true,
    "module": "NodeNext",
    "outDir": "dist"
  },
  "include": ["src"]
}

package.json (type of module or commonjs is ok)

  "type": "module",
  "scripts": {
    "build": "duel"
  }
npm run build

Now update the exports in package.json to match the build output in dist before you publish.

2
  • How does duel solve the dual package hazard?
    – Bergi
    Commented Jan 10 at 21:21
  • 2
    It delegates it to the user, i.e. ignores it completely. It exists, and you should know about it. Worry less, produce more.
    – morganney
    Commented Jan 10 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.