简体   繁体   English

如何将多个AMD模块捆绑在一个文件中?

[英]How do you bundle multiple AMD modules in a single file?

AMD seems to be the best practice to load javascript modules as-needed. AMD似乎是根据需要加载javascript模块的最佳实践。

This should work great on large web-apps where users only use a fraction of the available functionality. 在用户仅使用部分可用功能的大型Web应用程序上,这应该会很好用。

I've read about the optimizer, which concatenates all required modules into a single file, and I've read about no optimization, ie loading each module with a async request. 我已经读过关于优化器的信息,该优化器将所有必需的模块连接到一个文件中,并且我还读过关于无优化的信息,即使用异步请求加载每个模块。

Both don't seem to fit this use-case: loading every module with a request might quickly result in a large number of request, whereas optimizing forces you to download all the code. 两者似乎都不适合此用例:向每个模块加载请求可能会很快导致大量请求,而优化会迫使您下载所有代码。

Is there a way to bundle multiple modules into a single file? 有没有办法将多个模块捆绑到一个文件中?

Yes. 是。 Generally dividing application to so many files and loading them with AMD is only good for development . 通常,将应用程序划分为这么多文件,并用AMD加载它们仅对开发有利 It helps to keep the code clean and understandable; 它有助于保持代码的清洁和易于理解; it's quite logical that each module contains views, models, controllers and each of them is a separate file. 每个模块都包含视图,模型,控制器,并且每个视图都是一个单独的文件,这是很合乎逻辑的。

Yet that large number of request doesn't make sense in production . 但是大量的请求在生产中毫无意义 Thus you should use optimizer to compile and minimize files into one (or a few) to improve performance and user experience. 因此,您应该使用优化器将文件编译和最小化为一个(或几个)文件,以提高性能和用户体验。

If you're using RequireJS please refer to http://requirejs.org/docs/optimization.html#wholeproject — it explains how to use r.js tool provided by RequireJS. 如果您使用的是RequireJS,请参考http://requirejs.org/docs/optimization.html#wholeproject-它说明了如何使用RequireJS提供的r.js工具。

For example if my application was consisting of public area, administration and a very complex sign up form each build up with hundreds views/models/controllers I'd probably compile my code into just 4 files : common, public, admin, sign_up. 例如,如果我的应用程序由公共区域,管理和非常复杂的注册表单组成,每个表单都包含数百个视图/模型/控制器,则我可能会将代码编译成4个文件 :common,public,admin,sign_up。 Then appropriate file would be asynchronously loaded when user entered specific zone. 然后,当用户进入特定区域时,将异步加载适当的文件。

RequireJS supports this use-case with their optimization tool. RequireJS通过其优化工具支持此用例。

With the proper configuration in build.js, it can be configured to bundle multiple modules in multiple files. 通过在build.js中进行适当的配置,可以将其配置为将多个模块捆绑在多个文件中。

Their mapping can be defined in build.js as shown in this example project 如本示例项目所示,可以在build.js中定义它们的映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM