Skip to content

一些库暴露的是 ESModule,也有一些库暴露的是 CommonJS。需要将 CommonJS 转换为 ESModule,这样 Rollup 才能处理它们。@rollup/plugin-commonjs 应该在其他插件之前使用, 这是为了防止其他插件进行的更改破坏了 CommonJS 检测。

js
// sum.js
const sum = (a, b) => a + b

module.exports = sum
js
// RollupError: "default" is not exported by "src/sum.js", imported by "src/index.js".
import sum from "./sum"

export default sum
// index.js
npm i -D @rollup/plugin-commonjs
js
// rollup.config.mjs
import commonjs from '@rollup/plugin-commonjs'

export default {
  input: './src/index.js',
  output: {
    file: './dist/bundle.js',
    format: 'cjs'
  },
  // 将 CommonJS 转为 ESModule,报错消失。
  plugins: [commonjs()]
}