Indy
Indy

Reputation: 4957

ES2015 modules does not work in Node.js with Babel.js?

I want to use ES2015 modules in Node.js with babel.js compiler, but it won't work. Here is what I have:

package.json

{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
  },
  "devDependencies": {
    "babel-core": "^6.9.0",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-node5": "^11.1.0",
  }
}

.babelrc

{ "presets": ["es2015"], "plugins": [ "transform-runtime" ] }

server/index.js

require('babel-core').transform('code', {
  presets: ['node5'],
});

import { test } from './file1';

console.log(test);

server/file1.js

export const test = 'its working!';

But console throws error SyntaxError: Unexpected token import

Does ES2015 modules not working in node5, or I am doing something wrong here? Appreciate your help.

Upvotes: 1

Views: 266

Answers (1)

Dineshaws
Dineshaws

Reputation: 2083

Please install babel-register npm module and require this in index.js

server/index.js

require('babel-register');

import { test } from './file1';

console.log(test);

package.json

{
    "name": "test",
    "version": "0.0.1",
    "private": true,
    "scripts": {
     },
    "devDependencies": {
             "babel": "^6.5.2",
             "babel-preset-es2015": "^6.6.0",
             "babel-register": "^6.8.0"
    }
}

.babelrc

{presets:[es2015]}

for me it works

Thanks

Upvotes: 1

Related Questions