CLI scripts for ES6-powered packages with ESM
ESM to the rescue! Add
esm
to your project's package.json
as a dependency
(or peerDependency
if you want to leave its installation up to your package's consumer), and your users will then be able to run your script with node -r esm node_modules/path/to/script.js
.The only detail to pay attention to is to account for the difference between ES6's module system and CommonJS's:
const someES6Module = require("./path/to/module").default; // explicitly require default export if that is what you need
const namedExport = require("./path/to/module").namedExport; // named exports are to be referenced this way
// Or just use destructuring:
const { default: someES6Module, namedExport } = require("./path/to/module");