我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。
export class MyClass {
constructor() {
console.log("es6");
}
}
我试图在我的项目中运行一些ES6代码,但我得到了一个意外的令牌导出错误。
export class MyClass {
constructor() {
console.log("es6");
}
}
当前回答
此时没有必要使用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)
对于那些在2022年看到这篇文章的人来说,我也犯了同样的错误,但我把代码改成了这样:
module.exports = () => {
getUsers: () => users;
addUser: (user) => users.push(user);
};
我让模块工作了一段时间,然后它们没有出现这个Uncaught SyntaxError:意外的令牌导出错误。
结果是,我添加了一个开大括号而没有一个闭大括号。喜欢的东西:
if (true) {
/* } missing here */
export function foo() {}
虽然最大的错误是忘记了end},但解析器首先在大括号内找到一个导出,这是不允许的。
export关键字必须在文件的顶层。
So:
if (true) {
export function foo() {}
}
也不合法。当解析器遇到这种情况时,它立即停止解析,模糊地宣布错误使用了export,并给出与加载使用export关键字的“非模块”JavaScript文件时相同的错误。它从不报告底层缺少大括号错误。
我花了很长时间才弄明白,所以我在这里发帖,以帮助未来的患者。
理想情况下,解析器将报告只允许在文件的顶层导出。
实际上我想添加一个简单的解决方案。使用常量反撇号(')。
const model = `<script type="module" src="/"></<script>`
我通过制作一个入口点文件来解决这个问题。
// index.js
require = require('esm')(module)
module.exports = require('./app.js')
我在app.js内外导入的任何文件都可以使用导入/导出 现在你可以像node index.js一样运行它
注意:如果app.js使用export default,在使用入口点文件时,这将变成require('./app.js').default。