Chrome 61: Unexpected token import

折月煮酒 提交于 2019-12-17 18:37:10

问题


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"


回答1:


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};



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/46306148/chrome-61-unexpected-token-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!