Chrome 61: Unexpected token import

2020-02-04 07:19发布

Running Chrome 61 which is supposed to support module loading with import.

Indeed Paul's demo works for me. However, when I try it myself I get a JS error "Unexpected token import". Chrome seems to balk at 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"
}

Why does Chrome not understand "import"

3条回答
smile是对你的礼貌
2楼-- · 2020-02-04 07:39

Finally... figured it out. chrome://flags search for import enable ES6 import syntax. Restart Chrome. Be happy.

查看更多
淡お忘
3楼-- · 2020-02-04 07:41

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".

First the 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:

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

const squareArea = s => s * s;

export {circleArea, squareArea};
查看更多
Deceive 欺骗
4楼-- · 2020-02-04 08:01

That should be <script type=module src=test.js>. The entire syntax is subtly changed in module scripts (import and export are allowed, as well as strict mode being mandatory).

查看更多
登录 后发表回答