Can't import npm modules in commonjs with rollup : "require is not defined"

Art*_*sah 5 javascript rollup commonjs node.js ecmascript-6

I work on an ES6 project that I transpile using rollup and babel. It works well except when I try to import npm modules that use commonjs (and particularly require('something')) getting an error "require is not defined" in my browser (which means it hasn't properly compiled node modules from commonjs to ES5). However, I use rollup-plugin-node-resolve and rollup-plugin-commonjs, that should do that job if I've understood properly...

Here are my rollup config file:

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/**',
    })
  ],
};
Run Code Online (Sandbox Code Playgroud)

and my babel config file:

{
    "presets": [
        [
           "es2015",
           {
                "modules": false
            }
        ]
    ],
    "plugins": ["external-helpers"]
}
Run Code Online (Sandbox Code Playgroud)

Examples of modules that I can't load are math.js, nsolvejs, chroma.js, data.gui, etc.

Isi*_*osa 5

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

 commonjs({
    include: 'node_modules/**'
 })
Run Code Online (Sandbox Code Playgroud)