[英]Programmatically loading a ES6 module with Traceur in web page
I have been using Traceur to develop some projects in ES6. 我一直在使用Traceur在ES6中开发一些项目。 In my HTML page, I include local Traceur sources:
在我的HTML页面中,我包括了Traceur本地资源:
<script src="traceur.js"></script>
<script src="bootstrap.js"></script>
and if I have a module in the HTML afterwards like: 如果我以后在HTML中有一个模块,例如:
<script type="module" src="foo.js"></script>
Then Traceur loads in that module, compiles it and everything works great. 然后Traceur加载到该模块中,对其进行编译,然后一切正常。
I now want to programmatically add an ES6 module to the page from within another ES6 module (reasons are somewhat complicated). 我现在想以编程方式从另一个ES6模块中向页面添加ES6模块(原因有些复杂)。 Here was my first attempt:
这是我的第一次尝试:
var module = document.createElement('script');
module.setAttribute('type', 'module');
module.textContent = `
console.log('Inside the module now!');
`;
document.body.appendChild(module);
Unfortunately this doesn't work as Traceur does not monitor the page for every script tag added, I guess. 不幸的是,这不起作用,因为Traceur不会监视添加的每个脚本标记的页面。
How can I get Traceur to compile and execute the script? 如何让Traceur编译和执行脚本? I guess I need to invoke something on either 'traceur' or '$traceurRuntime' but I haven't found a good online source of documentation for that.
我想我需要在'traceur'或'$ traceurRuntime'上调用某些东西,但是我还没有找到一个很好的在线文档来源。
You can load other modules using ES6 import
statements or TraceurLoader
API for dynamic dependencies. 您可以使用ES6
import
语句或TraceurLoader
API加载其他模块以获得动态依赖关系。
Example from Traceur Documentation Traceur文档中的示例
function getLoader() {
var LoaderHooks = traceur.runtime.LoaderHooks;
var loaderHooks = new LoaderHooks(new traceur.util.ErrorReporter(), './');
return new traceur.runtime.TraceurLoader(loaderHooks);
}
getLoader().import('../src/traceur.js',
function(mod) {
console.log('DONE');
},
function(error) {
console.error(error);
}
);
Also, System.js loader seems to be supported as well 另外,似乎也支持System.js加载程序
window.System = new traceur.runtime.BrowserTraceurLoader();
System.import('./Greeter.js');
Dynamic module loading is a (not-yet-standardized) feature of System
: 动态模块加载是
System
的(尚未标准化)功能:
System.import('./repl-module.js').catch(function(ex) {
console.error('Internal Error ', ex.stack || ex);
});
To make this work you need to npm test
then include BrowserSystem 为此,您需要进行
npm test
然后包含BrowserSystem
<script src="../bin/BrowserSystem.js"></script>
You might also like to look into https://github.com/systemjs/systemjs as it has great support for browser loading. 您可能还想研究一下https://github.com/systemjs/systemjs,因为它对浏览器加载具有强大的支持。
BTW the System
object may eventually be standardize (perhaps under a different name) in the WHATWG: http://whatwg.github.io/loader/#system-loader-instance 顺便说一句,
System
对象最终可能会在WHATWG中进行标准化(也许使用其他名称): http ://whatwg.github.io/loader/#system-loader-instance
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.