ES2015模块在带有Babel.js的Node.js中不起作用?

时间:2016-05-20 10:02:13

标签: node.js ecmascript-6 babeljs

我想在Node.js中使用带有babel.js编译器的ES2015模块,但它不起作用。这就是我所拥有的:

的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" ] }

服务器/ index.js

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

import { test } from './file1';

console.log(test);

服务器/ file1.js

export const test = 'its working!';

但是控制台抛出错误SyntaxError: Unexpected token import

ES2015模块是否在node5中不起作用,或者我在这里做错了什么?感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

请安装babel-register npm模块并在index.js

中要求

服务器/ 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]}

对我来说它有效

由于