javascript Chrome 61:意外的令牌导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46306148/
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
Chrome 61: Unexpected token import
提问by Marc
Running Chrome 61 which is supposed to support module loadingwith import.
运行 Chrome 61,它应该支持使用import.
Indeed Paul's demoworks for me. However, when I try it myself I get a JS error "Unexpected token import". Chrome seems to balk at import:
事实上,保罗的演示对我有用。但是,当我自己尝试时,出现 JS 错误“意外的令牌导入”。Chrome 似乎犹豫import:
test.html
测试.html
<!doctype html>
<html>
<body>
<script src="test.js"></script>
</body>
</html>
test.js:
测试.js:
import {hello} from './something.js'
console.log(hello())
something.js
东西.js
export {hello}
function hello() {
return "hello world"
}
Why does Chrome not understand "import"
为什么 Chrome 不理解“导入”
采纳答案by David Ayres
For those of you who want to know exactly what worked for me, it was kind of a combination of a couple answers from above. I also had to enable the ES6 import capabilities of Chrome by typing chrome://flags in the URL bar and searching for "import".
对于那些想确切知道什么对我有用的人,这是上面几个答案的组合。我还必须通过在 URL 栏中键入 chrome://flags 并搜索“导入”来启用 Chrome 的 ES6 导入功能。
First the HTML:
首先是 HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Testing JavaScript Stuff</title>
</head>
<body>
<script type="module">
import { circleArea, squareArea } from './CalcArea.js';
console.log(circleArea(2));
console.log(squareArea(2));
</script>
</body>
</html>
So as you can see just add the type "module" to your script tag, then below you do the import. For my test the CalcArea.js file is this:
如您所见,只需将类型“模块”添加到您的脚本标签,然后在下面进行导入。对于我的测试,CalcArea.js 文件是这样的:
const circleArea = r => 3.14 * (r ** 2);
const squareArea = s => s * s;
export {circleArea, squareArea};
回答by Josh Lee
That should be <script type=module src=test.js>. The entire syntax is subtly changed in module scripts (importand exportare allowed, as well as strict mode being mandatory).
那应该是<script type=module src=test.js>。整个语法在模块脚本中进行了微妙的更改(import并且export是允许的,并且严格模式是强制性的)。
回答by flcoder
Finally... figured it out. chrome://flagssearch for importenable ES6 import syntax. Restart Chrome. Be happy.
终于……想通了。 chrome://flags搜索import启用 ES6 导入语法。重新启动 Chrome。要开心。

