头图

How to make an npm package that supports both cjs and esm?

趁你还年轻浙江
中文

Modularity is a commonplace issue, and packaging tools are emerging one after another.

So, how to use these packaging tools to create npm packages that support both cjs and esm.

This article does not involve concepts, it is some packaged tests.

demo repo: https://github.com/FrankKai/npm-bundle-demo

You can clone it and build the test locally.

  • tsc
  • rollup
  • webpack
  • esbuild

tsc

  • tsconfig.json
  • tsconfig-esm.json
  • package.json

cjs

tsconfig.json

 {
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "outDir": "./dist/cjs",
    "esModuleInterop": true,
    "moduleResolution": "node"
  }
}

esm

tsconfig-esm.json

 {
  "extends": "./tsconfig.json",

  "compilerOptions": {
    "target": "es2015",
    "module": "es2015",
    "outDir": "./dist/esm",
    "moduleResolution": "node"
  }
}

package.json

 {
  "main": "./dist/cjs/index.js",
  "module": "./dist/esm/index.js",
  "scripts": {
    "build": "rm -rf dist && tsc -p tsconfig.json && tsc -p tsconfig-esm.json"
  },
}

rollup

  • rollup.config.js
  • package.json

rollup.config.js

 export default [
  {
    input: "src/index.js",
    output: [
      { file: "dist/index.cjs.js", format: "cjs" },
      { file: "dist/index.esm.js", format: "es" },
    ],
  },
];

package.json

 {
  "main": "dist/index.cjs.js",
  "module": "dist/index.esm.js",
  "scripts": {
    "build": "rollup -c",
  },
}

webpack

  • webpack.config.js
  • package.json

webpack.config.js

 const path = require("path");

module.exports = {
  mode: 'none',
  entry: {
    "index.cjs": {
      import: './src/index.js',
      library: {
        type: 'commonjs2',
      },

    },
    "index.esm": {
      import: './src/index.js',
      library: {
        type: 'module',
      },
    },
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "[name].js",
    clean: true,
  },
  experiments: {
    outputModule: true
  }
};

package.json

 {
  "main": "dist/index.cjs.js",
  "module": "dist/index.esm.js",
  "scripts": {
    "build": "webpack",
  },
  "devDependencies": {
    "webpack": "^5.38.1",
    "webpack-cli": "^4.7.2"
  }
}

esbuild

  • package.json

     {
    "main": "dist/index.cjs.js",
    "module": "dist/index.esm.js",
    "scripts": {
      "esbuild:cjs": "esbuild ./src/index.js --bundle --outfile=dist/index.cjs.js --format=cjs",
      "esbuild:esm": "esbuild ./src/index.js --bundle --outfile=dist/index.esm.js --format=esm",
      "build": "npm run esbuild:cjs && npm run esbuild:esm"
    },
    "devDependencies": {
      "esbuild": "^0.14.49"
    },
    }
阅读 1.3k

趁你还年轻,做个优秀的前端工程师
努力成为优秀的前端工程师! 文章在微信公众号:大大大前端 同步更新,期待你的关注~
4k 声望
4.1k 粉丝
0 条评论
4k 声望
4.1k 粉丝
宣传栏