简体   繁体   English

合并多个Javascript文件的最佳做法是什么?

[英]What is the best practice to consolidate multiple Javascript files?

For CSS, I can use SASS to import one CSS file to another and produce only single CSS file. 对于CSS,我可以使用SASS将一个CSS文件导入另一个CSS文件并仅生成单个CSS文件。 What is the similar method for Javascript files? Javascript文件的类似方法是什么?

You might want to check out Closure Compiler (which is a Google product). 您可能想查看Closure Compiler (这是一个Google产品)。

You would probably want the Closure Compiler Application form of the product. 您可能需要产品的Closure Compiler Application表单。

A sample workflow would probably look like: 示例工作流程可能如下所示:

  1. Create a list of your JS files and paths 创建JS文件和路径的列表
  2. Run the command to compile and concatenate files ( java --jar compiler.js --js path_to_file1.js --js path_to_file2.js (etc.) compiled.js ) 运行命令来编译和连接文件( java --jar compiler.js --js path_to_file1.js --js path_to_file2.js (etc.) compiled.js

Closure Compiler also has a related project, Closure Stylesheets , that does the same thing for stylesheets. Closure Compiler还有一个相关的项目Closure Stylesheets ,它为样式表做了同样的事情。

This approach, of course means that there's a pre-compilation step. 这种方法当然意味着有一个预编译步骤。 Depending on your backend, there also exist libraries that do the compilation when the page is built. 根据您的后端,还有一些库在构建页面时进行编译。 For example, for JSP, there's Granule a tag library that creates the compiled JS and CSS files at page build. 例如,对于JSP, Granule是一个标记库,它在页面构建时创建已编译的JS和CSS文件。

There's a third possibility: modularization. 还有第三种可能性:模块化。 Since you gave the example of being able to import CSS files in SASS, an analogue for JavaScript is using a module library, using either the CommonJS standard , or (the one I prefer), the AMD (asynchronous module definition) pattern, which I have personally used with RequireJS . 由于您给出了能够在SASS中导入CSS文件的示例,因此JavaScript的模拟使用模块库,使用CommonJS标准 ,或者(我更喜欢的),AMD(异步模块定义)模式,我亲自与RequireJS一起使用 RequireJS also comes with a nice optimizing tool that will bundle up (minify, compress, concat etc) all the required files for your application RequireJS还附带了一个很好的优化工具,可以捆绑(缩小,压缩,连接等)应用程序所需的所有文件

UPDATE UPDATE

Since you mentioned that you are using Django in the comments (might be useful to update the question with this info too), see if this answer helps too 既然你提到你在评论中使用Django(也可能有用这个信息更新问题),看看这个答案是否也有帮助


You could use minify which allows you to minify and combine javascript files. 您可以使用minify ,它允许您缩小和组合javascript文件。 It also works with CSS. 它也适用于CSS。

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

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