我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。

export class MyClass {
  constructor() {
    console.log("es6");
  }
}

当前回答

当我试图在我的项目中导入本地javascript模块时,我也得到了意外的令牌导出错误。当在index.html文件中添加脚本标记时,我通过将类型声明为模块来解决这个问题。

<script SRC = "。/path/to/the/module/" type = "module"></script> .

其他回答

要使用ES6,请添加babel-preset-env

在你的。babelrc中:

{
  "presets": ["@babel/preset-env"]
}

答案更新,感谢@ghanbari评论应用babel 7。

如果遇到此错误,也可能与将JavaScript文件包含到html页面的方式有关。在加载模块时,必须显式地声明这些文件。这里有一个例子:

//module.js:
function foo(){
   return "foo";
}

var bar = "bar";

export { foo, bar };

当你像这样包含脚本时:

<script src="module.js"></script>

你会得到错误:

Uncaught SyntaxError:意外的令牌导出

你需要包含一个type属性设置为"module"的文件:

<script type="module" src="module.js"></script>

然后它应该会像预期的那样工作,你已经准备好在另一个模块中导入你的模块了:

import { foo, bar } from  "./module.js";

console.log( foo() );
console.log( bar );

2022年更新

您正在使用EcmaScript模块(ESM或'ES6模块')语法,但您的环境不支持它。

v14.13.0之前的NodeJS版本不支持ESM(导出关键字语法),并使用CommonJS Modules (module. js Modules)。导出属性语法)。NodeJS v14.13.0及更新版本支持ESM,但必须先启用它。

解决方案:

If you are using NodeJS v14.13.0 or newer (which does support ESM) you can enable it by setting "type":"module" in your project package.json Refactor with CommonJS Module syntax (for older versions of NodeJS) Consider using TypeScript alongside ts-node or ts-node-dev npm packages (for instant transpilation at development time) and write TypeScript in .ts files Transpile ESM to CommonJS using esbuild (esbuild package on npm) configured to transpile your ES6 javascript to a CommonJS target supported by your environment. (babel is no longer recommended)

只需使用tsx作为运行时而不是节点。它将允许你使用正常的import语句,而不必将你的项目切换到type: module,也不必处理type: module的讨厌后果。此外,你还将获得TypeScript支持。

我的意见

出口

ES6

myClass.js

export class MyClass1 {
}
export class MyClass2 {
}

other.js

import { MyClass1, MyClass2 } from './myClass';

CommonJS替代

myClass.js

class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };

other.js

const { MyClass1, MyClass2 } = require('./myClass');

出口违约

ES6

myClass.js

export default class MyClass {
}

other.js

import MyClass from './myClass';

CommonJS替代

myClass.js

module.exports = class MyClass1 {
}

other.js

const MyClass = require('./myClass');