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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.