javascript 延迟模块加载在 ES6 中是如何工作的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30033152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:31:25  来源:igfitidea点击:

How does lazy module loading work in ES6

javascriptimportmodulelazy-loadingecmascript-6

提问by Adam Boduch

How can I lazily-loadES6 modules? By lazy, I mean I don't want to actually load modules that aren't needed. For example, here's something I can do with RequireJS:

如何延迟加载ES6 模块?通过懒惰,我的意思是我不希望实际加载的模块不需要。例如,这是我可以用 RequireJS 做的事情:

function someEventHandler() {
    var SomeModule = require('some-module'),
        module = new SomeModule();
    // ...
}

Something along the same lines doesn't appear to be possible using ES6 imports:

使用 ES6 导入似乎无法实现相同的内容:

// Doesn't appear to be valid...
function someEventHandler() {
    import SomeModule from 'some-module';
    var module = new SomeModule();
    // ...
}

Are there any viable techniques to only pull in dependencies when needed, using ES6 modules? Or is the only path to trace the full dependency graph and fetch everything up-front?

是否有任何可行的技术可以仅在需要时使用 ES6 模块引入依赖项?或者是跟踪完整依赖图并预先获取所有内容的唯一路径?

回答by lyschoening

The importstatement will only work in the very top of files, and it will load all of them. This is mainly to avoid potential issues with circular dependencies.

import语句仅适用于文件的最顶部,并且会加载所有文件。这主要是为了避免循环依赖的潜在问题。

There will also be a way to do asynchronous loading; however the specification doesn't seem to be finalized yet. The ES6 module loaderpolyfill package uses a method called System.import(moduleName)that returns a promise and the final specification is likely to look similar:

也会有异步加载的方法;然而,规范似乎还没有最终确定。该ES6模块加载填充工具包使用调用方法System.import(moduleName)返回一个承诺,最终的规范很可能类似于:

function someEventHandler() {
    System.import('some-module').then((SomeModule) => {
        var module = new SomeModule();
        // ...
    })
}

回答by SanjiMika

Example for lazyloading jQuery in ES6 :

在 ES6 中延迟加载 jQuery 的示例:

import('jquery').then((jquery) => {
     // Because jquery is the module, here is the new syntax for using this 
          window.$ = jquery.default;
          window.$('#id');
});