It’s great to see how many npm packages already come with ESM versions. Most common seems to be:
"main": "src/main.js",
"module": "dist/mypkg.esm.js",
import {x} from 'mypkg'; // bundler uses "module" entry
const {x} = require('mypkg');
Files in package:
mypkg/
src/
main.js # CommonJS
util.js # CommonJS
dist/
mypkg.esm.js # bundled
"main": "src/main.mjs",
import {x} from 'mypkg';
const {x} = require('mypkg/cjs');
Files in package:
mypkg/
src/
main.mjs
util.mjs
cjs/
index.cjs # main
util.cjs
- Rewrite, based on suggestions by @mgtitimoli
I believe it would better to have a
cjs
folder under the package with apackage.json
with the"type": "commonjs"
since all the files under this folder are gonna be of this type.So at the end the user would be able to require it like:
const mypkg = require("mypkg/cjs");