Omry Rozenfeld
Omry Rozenfeld

Reputation: 125

Adding only ES2015 module support to Node

I am trying to add to Node the functionality of import/export as it exists in ES6.

I know Babel can be used to gain all ES6 functionality, but what I wanna see is if there is a way I can use Babel to add only the import/export functionality and if so how?

Upvotes: 2

Views: 253

Answers (1)

sdgluck
sdgluck

Reputation: 27227

Yes, you can use the transform-es2015-modules-commonjs plugin.

This plugin transforms ES2015 modules to CommonJS.

Install it:

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

Declare it in your .babelrc:

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

If you find yourself needing to require the default export of a module that declares its exports using the ES2015 module syntax, you will have to do the following:

var defaultExport = require('./es2015-module').default

To avoid this, install the babel-plugin-add-module-exports plugin, and update your .babelrc:

npm install babel-plugin-add-module-exports --save
{
  "plugins": [
    "add-module-exports",
    "transform-es2015-modules-commonjs"
  ]
}

______

To use this Babel configuration in your application, use the babel-register require hook.

In your application's entry file, for example:

// index.js
require('babel-register')
require('./app.js')

Then start using the ES2015 module syntax:

// app.js
import something from './something'

Upvotes: 2

Related Questions