- Posted on October 10, 2018
If you are developing your own front-end JavaScript packages, chances are you use ES6 syntax in your codebase, especially the long-awaited module system. Browser compatibility is pretty much painless thanks to Babel, but things can get harder if you want your package to expose a CLI script (to generate code or whatever) that is meant to be ran through Node.js directly.

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