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

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

当前回答

我遇到过这个问题,我花了一个小时才找到我的问题。

问题是我正在将我的代码从非模块更改为模块,并且我忘记删除导入的脚本文件。

我的“table.js”文件有以下一行。这是模块文件。

export function tableize(tableIdentifier) {

我的“orderinquiry.js”文件有以下一行。

import { tableize, changeColumnSizesDynamic } from '../common/table.js';

我的“orderinquiry.html”有以下两行。

<script src='/resources/js/common/table.js'></script>
<script type='module' src='/resources/js/client/orderinquiry.js'></script>

而第二行很好,声明type='module。但是第一行直接链接到table.js,导致了意外的错误。一切开始工作时,我删除了第一个<脚本>。

其他回答

如果遇到此错误,也可能与将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 );

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

在你的。babelrc中:

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

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

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

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)

我的意见

出口

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');