javascript - "import"意外 token ? ( Chrome 62)

标签 javascript google-chrome

在尝试解决为什么 systemjs 找不到我安装的自定义库时(可能是后续问题),我在尝试“手动”执行操作时遇到了困难。

所以我有一个由 3 个文件组成的简单系统:

  • index.html
  • hi.js
  • hi2.js

索引只是:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>

<body>
<script src="hi.js"></script>
</body>
</html>

hi.js:

import * as hi from "hi2.js";

hi.myFunction();

hi2.js:

function myFunction() {
  alert('hi')
}
export { myFunction };

现在当我运行(使用 webstorm 和 chrome 62)上面的代码时,我得到以下错误,由(chrome)调试器报告: “未捕获的语法错误:意外的 token 导入”

这里发生了什么?我检查了 javascript 合规性 on mdn它告诉我 import 受 chrome 61 及更新版本支持。 - 我使用 chrome 62 进行测试。

那么这是怎么回事,如何让它发挥作用?

根据 recomendation我还将 html 行更改为 <script type="module" src="hi.js"></script> .那根本没有帮助,同样的错误。

最佳答案

你是对的,你的脚本标签需要 type="module":

<script src="hi.js" type="module"></script>
<!-- ---------------^^^^^^^^^^^^^       -->

您还需要在模块说明符上添加一个 ./ 前缀:

import * as hi from "./hi2.js";
// ------------------^^

这是为了让一个没有路径的说明符在事物发展的某个阶段具有特殊意义。来自 the WHAT-WG spec :

This restriction (that a relative URL specifier must start with /, ./, or ../ – T.J.) is in place so that in the future we can allow custom module loaders to give special meaning to "bare" import specifiers, like import "jquery" or import "web/crypto". For now any such imports will fail, instead of being treated as relative URLs.

当我使用未设置实验性标志的 Chrome 62 对您的文件进行这两项更改时,我收到了警报。

关于javascript - "import"意外 token ? ( Chrome 62),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182102/

相关文章:

javascript - 如何检测vue组件何时通过属性更新功能?

javascript - 解析没有逗号分隔符的json数据

Javascript:控制谷歌浏览器的打开选项卡音频音量控制

python - 在Python中通过selenium执行测试时,ChromeDriver应该放在哪里?

java - Selenium /网络驱动程序 : firefox/chrome browser opens but times out

javascript - 为什么有时过去传递给 Chrome 中的 requestAnimationFrame 的时间戳?

javascript - Onclick 按钮在选项标签中的 vue.js 中不起作用

javascript - 在 Canvas 中以 % 宽度居中圆圈

javascript - 在继续 $.each 函数中的下一个循环之前等待函数完成

google-chrome - 自签名 SSL 证书(添加到 Keychain 并标记为 Trusted)在 Chrome 中显示无效