在尝试解决为什么 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, likeimport "jquery"
orimport "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/