node.js中意外的保留字导入

Dra*_*tis 53 javascript importerror node.js ecmascript-6

我正在尝试运行node.js后端服务器.我unexpected reserved word在Node.js文件中导入时收到错误.

文件中的行core.module.js是:

'use strict';
import lodashMixins from './lodashMixins.js'
... other imports and configurations ...
Run Code Online (Sandbox Code Playgroud)

我启动简单的命令: node core.module.js

这并不罕见,但通常会发生在其他库中.我还没有看到Node.js的解决方案.我该怎么解决这个问题?我正在使用Windows Server.

编辑:我发现它是ES6,但我怎么能启动它?它看起来像应用程序的后端,但我不知道我应该使用什么命令来启动它而没有错误.

Sam*_*ami 51

import是的一部分ECMAScript 2015 (ES6) standardAmit上述当前未在本地的NodeJS实现.

所以你可以使用transpiler babel来运行你的es6脚本

npm install babel

基于这个答案的一个例子

app.js

 import {helloworld,printName} from './es6'
 helloworld();
 printName("John");
Run Code Online (Sandbox Code Playgroud)

es6.js

 module.exports = {
    helloworld: function() { console.log('hello world!'); },
    printName: function(name) { console.log(name); }
}
Run Code Online (Sandbox Code Playgroud)

require hookstart.js中使用

require("babel/register");
var app = require("./app.js");
Run Code Online (Sandbox Code Playgroud)

并启动您的应用程序

node start.js
Run Code Online (Sandbox Code Playgroud)

编辑 上面的答案是基于babel v5.8.23.对于babel >= v6

require hookstart.js中使用

require('babel-core/register');
require("./app.js");
Run Code Online (Sandbox Code Playgroud)

此外,默认情况下不启用转换.所以你需要安装一个preset.在这种情况下使用es2015

npm install babel-preset-es2015
Run Code Online (Sandbox Code Playgroud)

.babelrc在根文件夹中的文件中使用它

{
   "presets": ["es2015"]
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*mit 34

import关键字是ECMAScript 2015中模块功能的一部分,以及export一些其他规范.

它目前没有在NodeJS中本地实现,即使在最新版本(v0.12.7)上也没有,在ES2015"友好"的fork iojs中也不支持它.

你需要使用一个转换器来实现它.

[编辑]尽管存在一个没有任何作用的--harmony_modules标志,但在最新版本(v5.8)中它仍然不受支持.你最好的选择是使用babel,正如这里这里所解释的那样

  • 那么你为什么不问他们? (4认同)