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

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

当前回答

//✅使用模块。出口而不是出口 模块。出口= { 人, };

其他回答

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)

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

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

我的“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,导致了意外的错误。一切开始工作时,我删除了第一个<脚本>。

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

在你的。babelrc中:

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

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

安装babel包@babel/core和@babel/preset,这将把ES6转换为commonjs目标,因为node js不直接理解ES6目标

npm install --save-dev @babel/core @babel/preset-env

然后,您需要在项目的根目录中创建一个名为.babelrc的配置文件,并将这段代码添加到其中。

[“@babel/preset-env”]

此时没有必要使用Babel (JS已经变得非常强大),因为您可以简单地使用默认的JavaScript模块导出。查看完整教程

Message.js

module.exports = 'Hello world';

app.js

var msg = require('./Messages.js');

console.log(msg); // Hello World