When you want to publish both CommonJS and ES6 versions of an NPM module, you can follow these steps:
1. Project Structure Setup
First, set up the project structure appropriately. It is generally recommended to place the source code in a dedicated directory, such as src, and place the built code in separate directories: lib for CommonJS and es for ES6.
shell- src - index.js - lib - es - package.json
2. Write ES6 Source Code
Write ES6 source code in the src directory.
javascript// src/index.js export function add(a, b) { return a + b; }
3. Use Build Tools
Choose a suitable build tool, such as Babel, to transpile the source code. With Babel, you can transpile ES6 code into CommonJS format and output it to different directories.
Install the necessary Babel dependencies:
bashnpm install --save-dev @babel/core @babel/cli @babel/preset-env
Then add the Babel configuration file .babelrc:
json{ "presets": [ ["@babel/preset-env", { "modules": "auto", "targets": { "esmodules": true } }] ] }
Configure the package.json scripts to build both ES6 and CommonJS versions:
json"scripts": { "build:cjs": "babel src --out-dir lib --presets=@babel/env", "build:esm": "BABEL_ENV=esmodules babel src --out-dir es --presets=@babel/env", "build": "npm run build:cjs && npm run build:esm" }
4. Set package.json
In the package.json file, specify the entry points for different versions:
json{ "main": "lib/index.js", "module": "es/index.js", "scripts": { "build": "..." }, ... }
main: Points to the CommonJS entry file (for Node.js or older tools).module: Points to the ES6 module entry file (for modern tools and environments that support ES6 modules).
5. Publish to NPM
After building, ensure the code is tested and then publish to NPM:
bashnpm publish
With this setup, users can automatically select the appropriate version based on their environment when using your package.
Example Projects
You can examine popular open-source projects to learn how they organize their code and build, such as lodash-es or similar libraries.
By following this method, you can ensure your NPM module supports both older CommonJS environments and leverages the advantages of modern JavaScript environments.