babel-plugin-transform-commonjs-es2015-modules

CommonJS to ES2015 modules (export/import) transformation plugin for Babel

Usage no npm install needed!

<script type="module">
  import babelPluginTransformCommonjsEs2015Modules from 'https://cdn.skypack.dev/babel-plugin-transform-commonjs-es2015-modules';
</script>

README

babel-plugin-transform-commonjs-es2015-modules

CommonJS to ES2015 modules (export/import) transformation plugin for Babel

Use Case

Converting the CommonJS-formatted scripts in node_modules to ES2015 Modules syntax. Then Babel can transform to other formats such as AMD, UMD, or SystemJS.

Should support most popular CommonJS patterns. Especially code generated by Babel (so this should work with Browserify's Babelify).

See Also

Supported Syntax

// in:
var foo = require('bar');
// out:
import foo from 'bar';

// in:
var foo = require('bar').foo;
// out:
import { foo } from 'bar';

// in:
var foo = require('bar').baz;
// out:
import { baz as foo } from 'bar';

// in:
module.exports = require('foo');
// out:
export * from 'foo';

// in:
module.exports = foo;
// out:
export default foo;

// in:
module.exports.foo = require('bar');
// out:
export { default as foo } from 'bar';

// in:
module.exports.foo = bar;
// out:
export var foo = bar;

// in:
exports.foo = require('bar');
// out:
export { default as foo } from 'bar';

// in:
exports.default = foo;
// out:
export default foo;

// in:
exports.foo = bar;
// out:
export var foo = bar;

Installation

$ npm install babel-plugin-transform-commonjs-es2015-modules

Usage

Via .babelrc (Recommended)

.babelrc

{
  "plugins": ["transform-commonjs-es2015-modules"]
}

Via CLI

$ babel --plugins transform-commonjs-es2015-modules script.js

Via Node API

require("babel-core").transform("code", {
  plugins: ["transform-commonjs-es2015-modules"]
});