DEV Community

Discussion on: How to use ES6 import syntax in Node.js

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

How to make NPM module works both with ES6 and CommonJS:

Create ./index.mjs for ES6 and ./index.js for CommonJS.

// `./index.mjs`
import foo from 'bar';

export function foo() {}
export function bar() {}
Enter fullscreen mode Exit fullscreen mode
// `./index.js`
const foo = require('bar');

exports.foo = function () {};
exports.bar = function () {};
Enter fullscreen mode Exit fullscreen mode

In ./package.json file…

{
  "exports": {
    "import": "./index.mjs",
    "require": "./index.js"
  },
  "files": [
    "index.js",
    "index.mjs"
  ],
  "main": "index.mjs"
}
Enter fullscreen mode Exit fullscreen mode

Example: github.com/taufik-nurrohman/quote

Collapse
 
rsa profile image
Ranieri Althoff

It seems a terrible idea to duplicate the entirety of the code only because of the two or three first lines.

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman

Any better solution? Adding build tool to copy and convert the ES6 script into CommonJS script in the same project is too much. I do this manually since this is not a large project. I can live with that.

Thread Thread
 
rsa profile image
Ranieri Althoff

Yes, that's the point of transpilers, just add a build step that converts the code for you instead of doing it manually.

If that's a small project, and it will not be bundled into a web app (i.e. it's a Node package), then just use the CommonJS version. That's what I do in node-argon2.