Reputation: 1185
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.
Upvotes: 1
Views: 1634
Reputation: 106463
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.
Upvotes: 3