Node.js treats as ES modules:
- Files ending in
.mjs
- Files ending in
.js
ifpackage.json
'stype
field is set tomodule
Node.js treats as CommonJS modules:
- Files ending in
.cjs
- Files ending in
.js
ifpackage.json
'stype
field is set tocommonjs
or is missing (current default, always specifytype
for future-proofing)
Code in TypeScript and transpile to a package supporting both ES & CJS using Rollup.
Support both ES & CJS in package.json
:
{
"type": "commonjs",
"files": [
"dist"
],
"types": "./dist/index.d.ts",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"default": "./dist/index.mjs"
}
}
}
Package properties:
.js
files are treated as CommonJS modules with thetype
field set tocommonjs
.mjs
files are treated as ECMAScript modules (Node.js 12+ require no runtime flag)dist
folder is distributed on install with thefiles
field set to[ "dist" ]
(other files are distributed by default: package.json, README, LICENSE...)./dist/index.d.ts
is used by IDEs for autocompletion via thetypes
field./dist/index.js
is the entry point for the package run in Node.js 11- via themain
fieldexports
overridesmain
and defines multiple conditional entry points for the package run in Node.js 12+./dist/index.mjs
is the entry point for the package run in Node.js 12+ and loaded using animport
statement via theimport
conditional field./dist/index.js
is the entry point for the package run in Node.js 12+ and loaded using arequire
statement via therequire
conditional field./dist/index.js
is the fallback entry point for the package run in Node.js 12+ via thedefault
conditional field
Support ES & CJS transpilation in rollup.config.js
:
import pkg from "./package.json";
import typescript from "rollup-plugin-typescript2";
export default [
{
input: "./src/index.ts",
output: [
{
file: pkg.main,
format: "cjs",
exports: "named",
sourcemap: true
},
{
file: pkg.module,
format: "esm",
exports: "named"
}
],
plugins: [
typescript({
tsconfigOverride: {
compilerOptions: {
declaration: true,
module: "ES2015",
strict: true,
target: "ES2015"
}
},
typescript: require("typescript")
})
]
}
]
Transpile package:
rollup --config rollup.config.js
# List scripts in package.json
npm run
# Run a script
npm run <scriptname>