简体   繁体   中英

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. What is the similar method for Javascript files?

You might want to check out Closure Compiler (which is a Google product).

You would probably want the Closure Compiler Application form of the product.

A sample workflow would probably look like:

  1. Create a list of your JS files and paths
  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 )

Closure Compiler also has a related project, Closure Stylesheets , that does the same thing for 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.

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 . RequireJS also comes with a nice optimizing tool that will bundle up (minify, compress, concat etc) all the required files for your application

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


You could use minify which allows you to minify and combine javascript files. It also works with CSS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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