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

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

当前回答

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

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

其他回答

在最新版本的Nodejs (v17?)中,您可以通过使用.mjs文件扩展名来使用顶级的“import”,“async”,“await”-而不是transpiling或变通方法。

   // > node my.mjs
   
   import {MyClass} from 'https://someurl'
   async func () {
     // return some promise
   }
   await func ()

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

可能的答案

我有这个问题,在我的情况下发生的是,我缺乏添加扩展到文件 < <文件。ts > >

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,请添加babel-preset-env

在你的。babelrc中:

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

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