Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome 61: Unexpected token import

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"

like image 426
Marc Avatar asked Sep 19 '17 17:09

Marc


3 Answers

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

like image 172
Josh Lee Avatar answered Nov 14 '22 14:11

Josh Lee


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};
like image 28
David Ayres Avatar answered Nov 14 '22 15:11

David Ayres


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

like image 2
flcoder Avatar answered Nov 14 '22 14:11

flcoder