[英]Load JS modules conditionally (SystemJS)
I am currently using jspm and SystemJS to load ES6 modules. 我目前正在使用jspm和SystemJS来加载ES6模块。 However, I would like to be able to 但是,我希望能够
Scan the page for certain selectors (eg, id
, data-plugin
) 扫描页面以查找某些选择器(例如, id
, data-plugin
)
Map these selectors to their module dependencies 将这些选择器映射到它们的模块依赖项
Load only those modules 仅加载那些模块
My thought was to handle these imports through the single entry point, System.import('src/main')
, that has access to the document
. 我的想法是通过可以访问document
的单一入口点System.import('src/main')
来处理这些导入。 I could then find the relevant selectors, map those selectors to modules, and then import
those modules. 然后,我可以找到相关的选择器,将这些选择器映射到模块,然后import
这些模块。
src/main
would look something like this: src/main
看起来像这样:
['d3', 'jquery'].forEach(function(dependency) {
import dependency;
});
This is not a viable solution as it is invalid syntax. 这不是一个可行的解决方案,因为它是无效的语法。 Is there a better way to achieve dynamic module loading in this sense? 在这种意义上,有没有更好的方法来实现动态模块加载?
Normal import
syntax can't be used to conditionally load modules, as you've already seen. 正如您已经看到的那样,正常import
语法不能用于有条件地加载模块。 To get around this, we can use the programmatic API provided by System
. 为了解决这个问题,我们可以使用System
提供的编程API。 You're already familiar with this API, since you use it to System.import('src/main');
您已经熟悉此API,因为您将它用于System.import('src/main');
. 。
To conditionally load modules, instead of using the import
keyword, you just have to continue using the System.import
method. 要有条件地加载模块,而不是使用import
关键字,您只需继续使用System.import
方法。
An example of this: 一个例子:
<!DOCTYPE html>
<html>
<head>
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
</head>
<body>
<div id='one'>One</div>
<div>Two</div>
<script>
System.import('main');
</script>
</body>
</html>
const map = {
'#one': 'one',
'#two': 'two'
};
for (let selector in map) {
if (document.querySelector(selector)) {
System.import(map[selector]);
}
}
window.HAS_ONE = true;
window.HAS_TWO = true;
In this example, window.HAS_ONE
would be defined, but window.HAS_TWO
would remain undefined
. 在这个例子中, window.HAS_ONE
将被定义,但window.HAS_TWO
将保持undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.