babel-plugin-transform-import-commonjs

Transform ES2015 import to CommonJS require

Usage no npm install needed!

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

README

babel-plugin-transform-import-commonjs

Fork of https://github.com/kiurchv/babel-plugin-transform-system-import-commonjs that compiles import instead of System.import, now that the import() proposal has been accepted.

Babel plugin that transforms ES2015 import into CommonJS require.

https://github.com/tc39/proposal-dynamic-import

How this works

This plugin transforms

var myModule = "./path/to/myModule";

import(myModule).then(function (module) {
  console.log(module);
});

to

var myModule = "./path/to/myModule";

new Promise(function(resolve) {
  resolve(require(myModule));
}.bind(this)).then(function (module) {
  console.log(module);
});

Requirements

You need support for Promise, use polyfill if needed.

Installation

$ npm install babel-plugin-transform-import-commonjs

Usage

Via .babelrc (Recommended)

.babelrc

{
  "plugins": ["transform-import-commonjs"]
}

Via CLI

$ babel --plugins transform-import-commonjs script.js

Via Node API

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