【问题标题】:How are modules loaded dynamically if there is only a single bundled JavaScript file?如果只有一个捆绑的 JavaScript 文件,如何动态加载模块?
【发布时间】:2016-11-24 04:12:44
【问题描述】:

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

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

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

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

【问题讨论】:

  • 该包仅包含 required 或其他文件(取决于捆绑器),因此您可以在项目中拥有大量模块(或者更有可能是正在构建项目的框架in) 并且只有您在应用中明确使用的那些会被捆绑。
  • Webpack 不是一个模块加载器,它是一个模块 bundler。正如您所说,它将所有代码组合到一个文件中。这是非常不同的,任何地方都不会发生动态加载。
  • @Sami:除非你进行代码拆分,这是非常值得鼓励的。

标签: javascript webpack bundling-and-minification


【解决方案1】:

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

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

【讨论】:

  • 那么是否推荐使用带有模块加载器的 Webpack 来两全其美?或者当您提到“支持模块加载的环境”时,您是指支持 ES6 module loading 的浏览器还是其他什么?
  • @atconway 这取决于您的要求。对于许多人来说,带有代码拆分的 Webpack 可能是一个好主意。是的,我的意思是原生 ES6 支持,当然在 web 中它可能仍然会从捆绑中受益,因为这意味着更少的加载。但是在任何情况下你都不需要带有 Webpack 的模块加载器。
【解决方案2】:

正如其他人所建议的,您可能感兴趣的是 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');
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    相关资源
    最近更新 更多