1

I'm trying to understand how ES6 export works.

Here are two local files:

main.html:

<script src="module.js"></script>
<script>
    import {hello} from './module'; // Tried both "module" and "module.js"
    let val = hello();
    alert(val);
</script>

module.js:

export function hello() {
    return 'Hello';
}

Expected result: alert with "Hello" text in it. Actual result: errors:

module.js - line 1: Unexpected token export

main.html - line 3: Unexpected token {

How to make it work?

PS. Tested in Chrome 67.

Community
  • 1
  • 1
john c. j.
  • 490
  • 1
  • 20
  • 59
  • 1
    I guess that error is due to the lack of browser support :/ – Jonas Wilms Jun 14 '18 at 14:45
  • 1
    all browser (and versions) cannot support it. it should be transpiled before it can be used; with, for e.g: babel – kiddorails Jun 14 '18 at 14:45
  • 1
    You should use a transpiler like babel – Naramsim Jun 14 '18 at 14:46
  • 2
    Add `type="module"` to your ` – Dominic Jun 14 '18 at 14:46
  • @JonasW. Tested in Chrome 67. I tend to think that ES6 export works in Chrome, though I'm not sure. – john c. j. Jun 14 '18 at 14:47
  • @DominicTobias Thank you. Yes, after I changed the 1st line, I got another error: about CORS policy. So, I restarted Chrome with [CORS restrictions disabled](https://stackoverflow.com/a/3177718). But then I got another new error: `module.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of ""`. I haven't fixed this new error for now, [but it seems it doesn't have "nice" workarounds](https://stackoverflow.com/questions/47403478). Actually I need this for Chrome extension and probably Chrome extensions have some good way to deal with MIME types. – john c. j. Jun 14 '18 at 15:10
  • Note that I just had a similar experience though the problem was a missing `}`. I can't say I love that the error was ` Unexpected token export` but I guess it makes sense from a certain point of view. – Joel Berger Aug 23 '18 at 22:02

1 Answers1

3

Full support of JavaScript modules have been added to Chrome since version 61. Here's the essential part you apparently missed in the doc:

Modules must be eventually included in your HTML with type="module", which can appear as an inline or external script tag.

You don't have to use the first script; import will direct browser to download the required module. So this should be enough:

<script type="module">
    import {hello} from './module.js';
    let val = hello();
    alert(val);
</script>

There's a caveat, however: you won't be able to serve modules from filesystem directly in Chrome - you'll need to either set up a 'regular' HTTP server or apply workarounds described in this thread.

raina77ow
  • 91,589
  • 12
  • 180
  • 210