[英]Unexpected tokens on ES6 export
I'm trying to understand how ES6 export works. 我试图了解ES6导出的工作原理。
Here are two local files: 这是两个本地文件:
main.html : 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 : module.js :
export function hello() {
return 'Hello';
}
Expected result: alert with "Hello" text in it. 预期结果:警告“Hello”文本。 Actual result: errors: 实际结果:错误:
module.js - line 1: Unexpected token
export
module.js - 第1行:意外的令牌export
main.html - line 3: Unexpected token
{
main.html - 第3行:意外的令牌{
How to make it work? 如何使它工作?
PS. PS。 Tested in Chrome 67. 在Chrome 67中测试过。
Full support of JavaScript modules have been added to Chrome since version 61 . 自版本61以来 ,Chrome已添加对JavaScript模块的完全支持。 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. 模块最终必须包含在HTML中,其类型为“模块” ,它可以显示为内联或外部脚本标记。
You don't have to use the first script; 您不必使用第一个脚本; import
will direct browser to download the required module. import
将直接浏览器下载所需的模块。 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 . 但是有一点需要注意:您将无法直接在Chrome中从文件系统提供模块 - 您需要设置“常规”HTTP服务器或应用此线程中描述的变通方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.