I’m trying to use ES6 modules in Chrome. From all the examples I’ve looked at the following seems to be the right way to do it, but when I run it in Chrome’s developer tools I get this error message…
uncaught SyntaxError: Unexpected token {
…highlighting the import statement in the module (script1.js, below) that’s trying to import the module. I’ve seen a lot of references to problems like this but none of the suggestions to remedy the situation have worked for me. If you could see what I’m doing wrong, I’d sure appreciate your help…
here’s the html…
<html> <head> <script src="lib1.js" type="module"></script> <script src="script1.js"></script> </head> <body> </body> </html>
here’s the module (lib1.js)…
export function doSomething() { alert("in module lib1"); }
here’s the script (script1.js) that tries to import the module…
import { doSomething } from "lib1.js"; doSomething();
Advertisement
Answer
EDIT: After about an hour of head scratching and finding out that my answer (pre-edit) was downvoted I got to this:
lib.js:
function doSomething() { console.log('in module lib'); } export {doSomething};
script.js:
import { doSomething } from './lib.js'; doSomething();
index.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="module" src="script.js"></script> </body> </html>
lib.js
, script.js
, and index.html
are on the same directory.
I added .js
to import { doSomething } from './lib.js';
because it didn’t work otherwise. According to Mozilla certain bundlers may permit or require the use of the extension for the module-name
.
But this only worked on Firefox Quantum (ver. 62.0.3). I enabled Experimental JavaScript on Chrome (ver. 70.0.3538.77) on:
chrome://flags/#enable-javascript-harmony
with no signs of success, but considering this worked on Firefox and that this compatibility table shows both Chrome and Firefox being on the same level of compatibility is making me more confused so I’ll probably end up asking a question regarding this whole thing.