rollup-plugin-commonjs
Convert CommonJS modules to ES6, so they can be included in a Rollup bundle
Installation
npm install --save-dev rollup-plugin-commonjs
Usage
Typically, you would use this plugin alongside rollup-plugin-node-resolve, so that you could bundle your CommonJS dependencies in node_modules
.
// rollup.config.js;; input: 'main.js' output: file: 'bundle.js' format: 'iife' plugins: ;
Usage with symlinks
Symlinks are common in monorepos and are also created by the npm link
command. Rollup with rollup-plugin-node-resolve
resolves modules to their real paths by default. So include
and exclude
paths should handle real paths rather than symlinked paths (e.g. ../common/node_modules/**
instead of node_modules/**
). You may also use a regular expression for include
that works regardless of base path. Try this:
commonjs({
include: /node_modules/
})
Whether symlinked module paths are realpathed or preserved depends on Rollup's preserveSymlinks
setting, which is false by default, matching Node.js' default behavior. Setting preserveSymlinks
to true in your Rollup config will cause import
and export
to match based on symlinked paths instead.
Custom named exports
This plugin will attempt to create named exports, where appropriate, so you can do this...
// importer.js; // exporter.jsmoduleexports = named: 42 ; // or `exports.named = 42;`
...but that's not always possible:
// importer.js; // my-lib.jsvar myLib = exports;myLibnamed = 'you can\'t see me';
In those cases, you can specify custom named exports:
Strict mode
ES modules are always parsed in strict mode. That means that certain non-strict constructs (like octal literals) will be treated as syntax errors when Rollup parses modules that use them. Some older CommonJS modules depend on those constructs, and if you depend on them your bundle will blow up. There's basically nothing we can do about that.
Luckily, there is absolutely no good reason not to use strict mode for everything — so the solution to this problem is to lobby the authors of those modules to update them.
License
MIT