SyntaxError:意外的令牌导入 [英] SyntaxError: Unexpected token import
问题描述
当我运行index.js时,它给出错误 SyntaxError:意外的令牌导入
。虽然我正在使用babel将ES6转换为ES5。
When I am running index.js its giving error SyntaxError: Unexpected token import
. Though I am using babel to convert ES6 to ES5.
package.json
package.json
{
"name": "espract",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"build": "babel src -d lib"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.3.17"
}
}
Person.js
Person.js
'use strict';
module.exports = class Person {
constructor(firstname, lastname) {
this.firstName = firstname;
this.lastName = lastname;
}
greet() {
console.log(`Hello, ${ this.firstName } ${ this.lastName }`);
}
};
index.js
import * as Person from './lib/Person';
//es class inherit Person
class Policeman extends Person {
constructor(firstname, lastname, badgenumber) {
//call parent constructor
super(firstname, lastname, badgenumber);
this.badgeNumber = badgenumber;
}
greet(){
//call parent class method
super.greet();
console.log(`License: ${this.badgeNumber}`);
}
}
var officer = new Policeman("John", "Solan", "1231341314134");
officer.greet();
注意:当我使用
var Person = require('./ lib / Person')
其
工作正常。
Note: When I am using
var Person = require('./lib/Person')
its working absolutely fine.
请指导我,我刚刚开始学习nodejs。
Please guide me I just started learning nodejs.
推荐答案
如果不需要,我建议不要使用Babel。正如您在评论中所述,如果您使用NodeJS 5.3.0版,您可能根本不需要Babel。
I would suggest not using Babel if it is not required. As you stated in your comment, if you use NodeJS version 5.3.0, you probably don't need Babel at all.
请看这篇文章:
NodeJS ES6兼容性列表
我建议只删除import语句,并用适当的要求(使用classic module.exports并将类 Person
导入正确的位置)进行替换。您的Node节点支持类和构造函数。
I would suggest only removing import statement and replacing it with proper require (using classic module.exports and importing class Person
in proper place). Classes and constructors are supported in your version of Node out of the box.
这篇关于SyntaxError:意外的令牌导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!