【问题标题】:ES6 Module throwing unexpected token errorES6 模块抛出意外的令牌错误
【发布时间】:2019-08-09 01:47:54
【问题描述】:

遇到这个问题,我感到非常震惊,但我们开始吧。我在控制台中收到错误:

Uncaught SyntaxError: Unexpected token {

在我的 index.js 文件中的这行代码上:

import { CountUp } from '/js/count-up.js';

该行是文件中的第一行,我在 HTML 页面上的脚本标记如下所示:

<script type="module" src='/js/count-up.js'></script>
<script src='index.js'></script>

我使用的是运行 Mojave 的 Macbook pro,并且使用的是 Chrome 73。

我真的不知道我哪里出错了,为什么我在一个简单的 es6 模块导入时得到一个未捕获的语法错误?

【问题讨论】:

  • 可以发count-up.js的内容吗?如果是外部库,请提供指向它的链接。

标签: javascript ecmascript-6 es6-modules


【解决方案1】:

&lt;script src='index.js'&gt; 缺少 type="module" 属性,因此它试图在不支持 ES6 模块语法(import 需要)的情况下加载它。


旁白:

删除:

<script type="module" src='/js/count-up.js'></script>

您只需要使用&lt;script&gt; 元素将入口点加载到您的JS 程序。 /js/count-up.js 是使用 import { CountUp } from '/js/count-up.js'; 加载的。

【讨论】:

  • 不是模块,是正则脚本
  • @AdamMcGurk — 它尝试import 一个模块。它需要对 ES6 模块的支持。
  • @AdamMcGurk 你需要type=module 使用importexport,要清楚
【解决方案2】:

在你的脚本声明中使用属性“type”:

https://github.com/inorganik/countUp.js/

“包含在您的 html 中。注意 type 属性”

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

【讨论】:

  • @AdamMcGurk 在你的 sn-p 中看起来不像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 2019-09-26
  • 2018-11-24
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多