获取意外的令牌导出

JavaScript Webpack

古一Green

2020-03-20

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

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

第2517篇《获取意外的令牌导出》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
DavaidTony宝儿 2020.03.20

使用ES6语法在节点中不起作用,不幸的是,您显然必须具有babel才能使编译器理解诸如导出或导入之类的语法。

npm install babel-cli --save

Now we need to create a .babelrc file, in the babelrc file, we’ll set babel to use the es2015 preset we installed as its preset when compiling to ES5.

At the root of our app, we’ll create a .babelrc file. $ npm install babel-preset-es2015 --save

At the root of our app, we’ll create a .babelrc file.

{  "presets": ["es2015"] }

Hope it works ... :)

Gil逆天 2020.03.20

如果出现此错误,则可能还与将javascript文件包含到html页面中的方式有​​关。加载模块时,您必须像这样明确声明这些文件。这里有个例子:

//module.js:
function foo(){
   return "foo";
}

var bar = "bar";

export { foo, bar };

当包含这样的脚本时:

<script src="module.js"></script>

您将收到错误:

未捕获的SyntaxError:意外的令牌导出

您需要包含类型属性设置为“模块”的文件:

<script type="module" src="module.js"></script>

然后它将按预期工作,并且您准备将模块导入另一个模块:

import { foo, bar } from  "./module.js";

console.log( foo() );
console.log( bar );
宝儿 2020.03.20

安装巴贝尔包@babel/core@babel/preset将ES6转换为CommonJS的目标为节点的js不直接了解ES6目标

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

然后,您需要.babelrc在项目的根目录中创建一个名称配置文件,并在其中添加此代码

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

泡芙 2020.03.20

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

并在您的.babelrc

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

由于@ghanbari的评论适用了babel 7,答案得到了更新。

飞云 2020.03.20

您正在使用ES6模块语法。

这意味着您的环境(例如,node.js)必须支持ES6模块语法。

NodeJS uses CommonJS Module syntax (module.exports) not ES6 module syntax (export keyword).

Solution:

  • Use babel npm package to transpile your ES6 to a commonjs target

or

  • Refactor with CommonJS syntax.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android