javascript requireJS 中的包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25175914/
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 04:07:05  来源:igfitidea点击:

bundles in requireJS

javascriptrequirejs

提问by user sks

I am new to requireJS and tring to learn it so that i can use it in my current application.
While reading API documentation of requireJS, I came across bundles(http://requirejs.org/docs/api.html#config-bundles) as configuration option of requireJS

我是 requireJS 的新手并试图学习它,以便我可以在我当前的应用程序中使用它。
在阅读 requireJS 的 API 文档时,我遇到了bundleshttp://requirejs.org/docs/api.html#config-bundles)作为 requireJS 的配置选项

requirejs.config({
    bundles: {
        'primary': ['main', 'util', 'text', 'text!template.html'],
        'secondary': ['text!secondary.html']
    }
});

require(['util', 'text'], function(util, text) {
    //The script for module ID 'primary' was loaded,
    //and that script included the define()'d
    //modules for 'util' and 'text'
});

API Explanation :
Bundles config is useful if doing a build and that build target was not an existing module ID, or if you have loader plugin resources in built JS files that should not be loaded by the loader plugin.

API 说明:
如果进行构建并且构建目标不是现有模块 ID,或者如果您在构建的 JS 文件中有加载器插件资源不应由加载器插件加载,则捆绑配置很有用。

But here I am not able to understand that why we need bundle and when we should use use it?

但是在这里我无法理解为什么我们需要 bundle 以及何时应该使用它?

回答by Tomer

When building a large SPA (Single Page App), it is imperative that you concatenate and minify your files. The problem with doing it, is that you might end up with one massive minified js file that can get as large as a few megs.

在构建大型 SPA(单页应用程序)时,您必须连接和缩小文件。这样做的问题是,您最终可能会得到一个巨大的缩小的 js 文件,该文件可以达到几兆。

In order to solve this, require introduces the bundle feature, which allows you to pack your files in several bundles, and those would be loaded only when needed.

为了解决这个问题,require 引入了 bundle 特性,它允许你将文件打包成多个包,并且只在需要时加载。

So, for example if you have a page with 'home' and 'about', you can create a bundle like:

因此,例如,如果您有一个包含“home”和“about”的页面,您可以创建一个类似如下的包:

bundles: {
        'home': ['home', 'util', 'text', 'text!home.html'],
        'about': ['text!about.html']
    }

and then the about page resources would only be served when you actually click the about page. That way you get lazy loading of resources.

然后只有当您实际单击关于页面时才会提供关于页面资源。这样你就可以延迟加载资源。

For better explanation and example, watch this great video: http://vimeo.com/97519516

如需更好的解释和示例,请观看此精彩视频:http: //vimeo.com/97519516

The relevant part is around the 39 min.

相关部分大约是 39 分钟。