运行功能从ecmascript 6模块加载 [英] Run function loaded from ecmascript 6 module
问题描述
我第一次尝试使用ecmascript 6模块系统。我使用traceur编译器。给定两个es6文件:
I try to use ecmascript 6 modules system for first time. I use traceur compiler. Given two es6 files:
// app.js
export function row() {
alert('row');
}
// init.js
import { row } from 'public_js/app';
row();
Traceur(我使用grunt-traceur任务)将它们编译为:
Traceur (I use grunt-traceur task) compiles them to:
// app.js
System.register("public_js/app", [], function() {
"use strict";
var __moduleName = "public_js/app";
function row() {
alert('row');
}
return {get row() {
return row;
}};
});
// init.js
System.register("public_js/init", [], function() {
"use strict";
var __moduleName = "public_js/init";
var row = System.get("public_js/app").row;
row();
return {};
});
我包含编译版本的 init.js
通过简单的脚本标签到我的HTML:
I include compiled version of init.js
to my HTML via simple script tag:
<script src="/path/to/compiled/init.js" type="module"></script>
没有任何反应。我没有看到我的警报。我做错了什么?
And nothing happens. I don't see my alert. What am I doing wrong?
推荐答案
通过将代码预先编译为ES5的模块,您现在将其从ES6自动导入/模块加载系统的世界,您需要使用ES5机制来加载它。因此,您需要包含编译代码而不使用 type = module
属性,然后 get()
启动世界其他地方的模块。
By pre-compiling your code as modules to ES5, you are now taking it out of the world of the automatic import/module loading system in ES6 and you need to use ES5 mechanisms to load it. So, you need to include the compiled code without the type=module
attribute and then get()
the module that kicks off the rest of the world.
所以,以下内容适用于我:
So, the following works for me:
<script src="/path/to/compiled/app.js"></script>
<script src="/path/to/compiled/init.js"></script>
<script>
System.get('public_js/init');
</script>
由于您是预编译代码,建议您将所有已编译的代码连接到单个JS文件,以避免包括它们全部。
Since you are pre-compiling the code, I recommend that you concatenate all of the compiled code into a single JS file to avoid including them all.
如果您先使用Traceur而不编译代码,那么您可以在ES6结构中生活。这包括 type =module
和/或 import'module-name'
。
If you use Traceur without compiling your code first, then you can live within the ES6 constructs. This includes type="module"
and/or import 'module-name'
.
编辑
进一步考虑这一点, app.js
正确地编译为模块。 init.js
,但不需要编译为模块。您正在使用 - module
标志来编译代码。如果以脚本
标记编译 init.js
,那么它不会封装 init
代码作为模块,您不需要手动调用 System.get
。只需要考虑一下。
Edit
Thinking about this further, app.js
is correctly compiled as a module. init.js
, however, doesn't need to be compiled as a module. You are compiling the code with the --module
flag. If, instead, you compile init.js
with the --script
flag, it will not encapsulate the init
code as a module, and you don't need to call System.get
by hand. Just something to think about.
这篇关于运行功能从ecmascript 6模块加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!