Chrome 61:意外的令牌导入

Mar*_*arc 21 javascript google-chrome es6-modules

运行Chrome 61是应该支持模块加载import.

确实,保罗的演示适合我.但是,当我自己尝试时,我得到一个JS错误"意外的令牌导入".Chrome似乎不愿意import:

的test.html

<!doctype html> 
<html>
<body>
<script src="test.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

test.js:

import {hello} from './something.js'
console.log(hello())
Run Code Online (Sandbox Code Playgroud)

something.js

export {hello}
function hello() {
    return "hello world"
}
Run Code Online (Sandbox Code Playgroud)

为什么Chrome不理解"导入"

Jos*_*Lee 19

那应该是<script type=module src=test.js>.整个语法在模块脚本中巧妙地改变(import并且export允许,并且严格模式是强制性的).

  • 使用type = module时,代码适用于我.尽管如此,Chrome开发人员工具在编辑文件时仍会在test.js中显示错误"Uncaught Syntax error:Unexpected token {".知道如何克服这个问题吗? (5认同)
  • 不要通过添加type = module工作,我使用chrome v67 (2认同)

Dav*_*res 3

对于那些想确切知道什么对我有用的人来说,这是上面几个答案的结合。我还必须通过在 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>
Run Code Online (Sandbox Code Playgroud)

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

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

const squareArea = s => s * s;

export {circleArea, squareArea};
Run Code Online (Sandbox Code Playgroud)