Minifying RequireJS Javascript codebase to a singl

2019-03-10 20:41发布

问题:

I am new to RequireJS and maybe this is an already discussed issue but I could not find a clear answer or opinion about this.

I have an application working with RequireJS. It has a lot of JavaScript files loaded by Require as they are needed. Working as expected.

Looking to Fiddler inspector I could see that all the files were loaded when the application started. I believe that Require has made a deep traversal of all the references to JavaScript files and loaded them all in the beginning.

If this is the way it works I believe that it would be better to generate a single file, minify it, and load it using a <script> html tag.

If I generate one single file with all scripts, and pre-load them with <script> will RequireJS load them again?

Am I doing something wrong?

In a production environment what could be the better solution?

Thanks in advance.

回答1:

What you want is the RequireJS Optimizer.

The optimizer does the following (from the docs):

  • Combines related scripts together into build layers and minifies them via UglifyJS (the default) or Closure Compiler (an option when using Java).
  • Optimizes CSS by inlining CSS files referenced by @import and removing comments.

Here's one article on the topic for further reference.

Have a look also at r.js, the command line tool which includes the optimizer. Using r.js, you can generate an optimized build from an application file main.js with just:

node r.js -o build.js

where build.js is a requirejs config file containing your build profile (baseUrl, paths, etc.).



标签: requirejs