Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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/**',
    })
  ],
};

and my babel config file:

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

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

like image 633
Arthur Pesah Avatar asked Sep 09 '17 13:09

Arthur Pesah


People also ask

Can you use import in CommonJS?

CommonJS modules cannot import ES Modules. You are not able to import . mjs files from . js files.

Is CommonJS deprecated?

It is not deprecated. ESM modules (ECMAScript modules) that use import and export are the new Javascript standard for modules and we can expect that nodejs will support these for as long as they are the Javascript standard (probably forever).

Does Node still use CommonJS?

CommonJS is a set of standards used to implement modules on JavaScript. The project was started by Mozilla engineer Kevin Dangoor in 2009. CommonJS is mainly used in server-side JS apps with Node, as browsers don't support the use of CommonJS.

What is CommonJS format?

CommonJS is a module formatting system. It is a standard for structuring and organizing JavaScript code. CJS assists in the server-side development of apps and it's format has heavily influenced NodeJS's module management.


1 Answers

The issue is probably with commonjs plugin, it is used to transform cjs into es modules at build time, therefore you should include the cjs modules from node_modules instead of src.

 commonjs({
    include: 'node_modules/**'
 })
like image 83
Isidrok Avatar answered Oct 14 '22 21:10

Isidrok