Chrome61:意外的令牌导入

Chrome 61: Unexpected token import

运行 Chrome 61 即 supposed to support module loadingimport.

保罗的 demo 确实对我有用。但是,当我自己尝试时,出现了 JS 错误 "Unexpected token import"。 Chrome 似乎对 import 犹豫不决:

test.html

<!doctype html> 
<html>
<body>
<script src="test.js"></script>
</body>
</html>

test.js:

import {hello} from './something.js'
console.log(hello())

something.js

export {hello}
function hello() {
    return "hello world"
}

为什么Chrome不明白"import"

应该是<script type=module src=test.js>。模块脚本中的整个语法发生了微妙的变化(importexport 是允许的,严格模式是强制性的)。

终于……想通了。 chrome://flags 搜索 import 启用 ES6 导入语法。重新启动 Chrome。开心点。

对于那些想确切知道什么对我有用的人来说,这是上面几个答案的组合。我还必须通过在 URL 栏中键入 chrome://flags 并搜索 "import".

来启用 Chrome 的 ES6 导入功能

首先是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>

正如您所见,只需将类型 "module" 添加到您的脚本标签中,然后在下方进行导入。对于我的测试,CalcArea.js 文件是这样的:

const circleArea = r => 3.14 * (r ** 2);

const squareArea = s => s * s;

export {circleArea, squareArea};