rollup | 解决报错Error: '__moduleExports' is not exported by xxxx

官方解释

Error: "[name] is not exported by [module]"

Occasionally you will see an error message like this:

'foo' is not exported by bar.js (imported by baz.js)

Import declarations must have corresponding export declarations in the imported module. For example, if you have import a from './a.js' in a module, and a.js doesn't have an export default declaration, or import {foo} from './b.js', and b.js doesn't export foo, Rollup cannot bundle the code.

This error frequently occurs with CommonJS modules converted by rollup-plugin-commonjs, which makes a reasonable attempt to generate named exports from the CommonJS code but won't always succeed, because the freewheeling nature of CommonJS is at odds with the rigorous approach we benefit from in JavaScript modules. It can be solved by using the namedExports option, which allows you to manually fill in the information gaps.

由于commonjs的某些特性,你必须显式指出某个文件的变量导出。

例如:

(我的一个react项目)

import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import json from 'rollup-plugin-json'

export default {
  input: './lib/main.js',
  output: {
    file: 'build/bundle.min.js',
    format: 'iife',
    name: 'saber2pr',
    banner: `var process = {
      env: {
        NODE_ENV: 'production'
      }
    }`
  },
  watch: {
    include: 'lib/**'
  },
  plugins: [resolve(), commonjs({
    'namedExports': {
      './lib/main.js': ['__moduleExports']
    }
  }), json()]
}

 

其中commonjs插件配置了选项,指明./lib/main.js文件的导出变量__moduleExports。

namedExports配置项的格式:

Options.namedExports?: {
    // 文件路径:[导出变量名]
    [key: string]: string[];
}

// 即键是文件路径,值是导出变量数组(字符串数组)。

 

然后重新运行rollup -c。

 

你可能感兴趣的:(rollup)