SyntaxError:意外的令牌导入

当我正在运行index.js它给错误SyntaxError: Unexpected token import 。 虽然我使用babel将ES6转换为ES5。

的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

 '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')它的工作非常好。

请指导我,我刚开始学习nodejs。

如果不需要,我会build议不要使用Babel。 正如您在评论中所述,如果您使用NodeJS 5.3.0版本,则可能根本不需要Babel。

请看这篇文章: NodeJS ES6兼容性列表

我build议只删除导入语句,并将其replace为适当的要求(使用经典的module.exports并在适当的位置导入类Person )。 开箱即用的Node版本支持类和构造函数。