Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

javascript - unexpected reserved word import in node.js

I'm trying to run node.js backend server. I've received error unexpected reserved word on import in Node.js file.

The lines in file core.module.js is:

'use strict';
import lodashMixins from './lodashMixins.js'
... other imports and configurations ...

I launch simple command: node core.module.js

It's not uncommon error, but usually it happens with other libraries. I haven't seen solution for Node.js. How should I fix this? I'm using Windows Server.

Edit: I've find out that it's ES6, but how could I launch it? It looks like backend for the application, but I have no idea what command should I use to launch it without errors.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

import is a part of ECMAScript 2015 (ES6) standard and as Amit above mentioned it is not currently implemented natively in Nodejs.

So you can use transpiler like babel to run your es6 script

npm install babel

An example based on this answer

app.js

 import {helloworld,printName} from './es6'
 helloworld();
 printName("John");

es6.js

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

And using require hook in start.js

require("babel/register");
var app = require("./app.js");

And start your app as

node start.js

EDIT The above answer was base on babel v5.8.23. For babel >= v6

Use require hook in start.js as

require('babel-core/register');
require("./app.js");

Also, transformations are not enabled by default. So you will need to install a preset. In this case use es2015

npm install babel-preset-es2015

And use it in a .babelrc file in root folder

{
   "presets": ["es2015"]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...