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

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

当前回答

我的意见

出口

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

其他回答

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

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

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

我通过制作一个入口点文件来解决这个问题。

// index.js
require = require('esm')(module)
module.exports = require('./app.js')

我在app.js内外导入的任何文件都可以使用导入/导出 现在你可以像node index.js一样运行它

注意:如果app.js使用export default,在使用入口点文件时,这将变成require('./app.js').default。

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

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

Message.js

module.exports = 'Hello world';

app.js

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

console.log(msg); // Hello World

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)