如果只有一个捆绑的 JavaScript 文件,如何动态加载模块?

How are modules loaded dynamically if there is only a single bundled JavaScript file?

我知道当使用像 webpack 这样的模块加载器时,结果输出将是一个像 bundle.js 这样的 JavaScript 文件。现在在index.html我只需要参考以下内容:

<script src="bundle.js"></script>

我的问题是,如果我只有一个 .js 文件,动态模块加载是如何发生的?也许我的理解偏离了这里,但是模块加载器的整个想法 不是 服务模块 .js 文件直到需要它吗?因此不必从应用程序开始加载所有文件 index.html。好吧,如果我已经提供了来自 index.html 的单个 bundle.js 文件,那么该文件中的单独模块如何异步提供并且仅在需要时提供?那时候我觉得我已经下载文件了,所以性能部分没有获得。

当整个应用程序只提供一个捆绑的 .js 文件时,模块加载器如何工作?

当您以这种方式使用 Webpack 时,您没有使用任何模块加载器或动态加载。 Webpack 是一个模块 bundler 这意味着它解析所有必需的模块,将它们组合成一个文件并允许您将其包含在您的网页中(或任何您想要使用代码的地方) .

如果您在支持模块加载的环境中工作,您甚至不需要 Webpack(这里不涉及缩小、转译或填充)。您只需使用模块加载即可。

正如其他人所推荐的,您可能会感兴趣的是 webpack 的代码拆分。 我也是webpack的新手,但是我是这样理解的

app.js:

var $ = require('jquery'); // adds contents of jquery.js into the global bundle

// do stuff on runtime

module.exports = (function () {

    // do stuff above the fold (but only if app() is called)

    // time to use a module from outside of our bundle
    require.ensure([
        "./below_the_fold.js" // here you define which files will the new chunk contain (it is created on webpack compile)
    ], (require) => {
        // callback after the chunk is dynamically loaded by JSONP

        var moduleBelow = require("./below_the_fold.js"); // this particular require() which is inside require.ensure doesn't add required file into the bundle

        // do stuff below the fold (that needs moduleBelow which is what below_the_fold.js exports)

    }, 'below_the_fold'); // optional name of chunk file

});

window.app = module.exports


below_the_fold.js:

module.exports = (() => {
    // some logic we don't want into our global bundle because it's heavy or rarely used

    console.log('doing stuff below the fold is now possible');
})();