无法使用汇总导入commonjs中的npm模块:“require is not defined”

时间:2017-09-09 13:07:21

标签: javascript node.js ecmascript-6 commonjs rollup

我参与了一个ES6项目,我使用汇总和babel进行了转换。它运行良好除非我尝试导入使用commonjs的npm模块(特别是要求('某些东西))在我的浏览器中收到错误“require not defined”(这意味着它没有正确编译从commonjs到的节点模块) ES5)。但是,我使用 rollup-plugin-node-resolve rollup-plugin-commonjs ,如果我理解正确的话,应该做这个工作......

以下是我的汇总配置文件:

import babel from 'rollup-plugin-babel';
import eslint from 'rollup-plugin-eslint';
import resolve from 'rollup-plugin-node-resolve'; // to import node_modules packages easily
import commonjs from 'rollup-plugin-commonjs'; // convert commonjs to es6 (in case you use require)

export default {
  input: 'src/main.js',
  output: {
      file:'build/index.js',
      format: 'iife'
  },
  sourcemap: 'inline',
  plugins: [
    resolve({
      jsnext: true,
      main: true,
      browser: true
    }),
    commonjs({
        include: 'src/**'
    }),
    eslint({
      exclude: [
        'src/styles/**',
      ]
    }),
    babel({
      exclude: 'node_modules/**',
    })
  ],
};

和我的babel配置文件:

{
    "presets": [
        [
           "es2015",
           {
                "modules": false
            }
        ]
    ],
    "plugins": ["external-helpers"]
}

我无法加载的模块示例是 math.js,nsolvejs,chroma.js,data.gui 等。

1 个答案:

答案 0 :(得分:2)

问题可能在于commonjs插件,它用于在构建时将cjs转换为es模块,因此你应该包含node_modules而不是src的cjs模块。

class Vehicle:
   __metaclass__=abc.ABCMeta
   def __init__(self):
      raise NotImplemetedError('The class cannot be instantiated')
   @abstractmethod
   def vehicletype(self):
       pass