javascript “导入”意外令牌?(铬62)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47182102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"import" unexpected token? (chrome 62)
提问by paul23
While trying to troubleshoot why systemjs didn't find a custom library I installed (could be a follow up question) I was stuck when trying to do things "manually".
在尝试解决为什么 systemjs 没有找到我安装的自定义库(可能是一个后续问题)时,我在尝试“手动”做事时被卡住了。
So I have a simple system that consists of 3 files:
所以我有一个由 3 个文件组成的简单系统:
- index.html
- hi.js
- hi2.js
- 索引.html
- hi.js
- hi2.js
the index is just:
该指数只是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<script src="hi.js"></script>
</body>
</html>
hi.js:
嗨.js:
import * as hi from "hi2.js";
hi.myFunction();
hi2.js:
hi2.js:
function myFunction() {
alert('hi')
}
export { myFunction };
Now when I run (using webstorm and chrome 62) above code, I get the following error, reported by the (chrome) debugger: "Uncaught SyntaxError: Unexpected token import"
现在,当我运行(使用 webstorm 和 chrome 62)上面的代码时,出现以下错误,由(chrome)调试器报告:“Uncaught SyntaxError: Unexpected token import”
What's happening here? I checked for javascript compliance on mdnand it tells me import is supported by chrome 61 and newer. - I use chrome 62 for testing this.
这里发生了什么事?我检查了mdn 上的javascript 合规性,它告诉我 chrome 61 和更新版本支持导入。- 我使用 chrome 62 来测试这个。
So what's going on, and how to make it work?
那么发生了什么,以及如何使其发挥作用?
Per recomendationI also changed the html line to <script type="module" src="hi.js"></script>. That didn't help at all, same error.
根据建议,我还将 html 行更改为<script type="module" src="hi.js"></script>. 那根本没有帮助,同样的错误。
回答by T.J. Crowder
You're correct that you need type="module"on your script tag:
你是正确的,你需要type="module"在你的脚本标签上:
<script src="hi.js" type="module"></script>
<!-- ---------------^^^^^^^^^^^^^ -->
You also need a ./prefix on your module specifier:
您还需要./在模块说明符上添加前缀:
import * as hi from "./hi2.js";
// ------------------^^
This is to leave the door open for a specifier with no path at all to have special meaning at some stage as things evolve. From the WHAT-WG spec:
这是为了让完全没有路径的说明符在事物发展的某个阶段具有特殊含义的大门敞开。来自WHAT-WG 规范:
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.
此限制(相对 URL 说明符必须以
/,./或../– TJ开头)已经存在,以便将来我们可以允许自定义模块加载器为“裸”导入说明符赋予特殊含义,例如import "jquery"或import "web/crypto"。目前,任何此类导入都将失败,而不是被视为相对 URL。
When I make those two changes to your files, with Chrome 62 with no experimental flags set, I get the alert.
当我对您的文件进行这两项更改时,Chrome 62 没有设置实验标志,我收到警报。

