Before the article has introduced the basic use of Requirejs, but the direct use of REQUIREJS will expose a problem, that is, when the module too much time, Requirejs will introduce many JS files, greatly increase the number of requests, then some friends will say, Our own compression of those module files is not OK, in fact, think carefully about this can not do, the answer is OK! But it's troublesome:
1. First of all, we write the module will not define the module name, because the module name is the default JS file name, if you manually write the module name, added extra work.
2. Loading order problem, self-compression, it is necessary to strictly control the order of the module (especially with jquery and jquery plug-in case), otherwise it is prone to error.
To solve these problems, Requirejs gives a solution, that is, R.js,r.js is for the modular development of REQUIREJS with the packaging compression problem. R.js Download
So here's how to use R.js to package and compress our modules:
1. Place the r.js in our project root directory.
2. Create a new built.js with content such as:
'./static/scripts/src/' ".. /.. /.. /main " ' jquery ': "Vendor/jquery/jquery" , ' Jquery.email ': "Plugin/jquery.email" ' aaa ':" Moudle/aaa/aaa " ' BBB ': "MOUDLE/BBB/BBB" , ' CCC ': "MOUDLE/CCC/CCC" ' jquery ' : {deps: [ "jquery" "JQuery.fn.hEmail" }}, out: "main-built.js"
Built is actually a packaged compressed configuration file, here I use the previous article in the initial Requirejs (a) in the example, so that the Built.js code is not very familiar with, like require configuration JS? The fact is similar, let us explain the very same part, name is actually that Requirejs's entrance file, output is the file name after packaging, and a property called Dir, which I do not use, is used to configure the output of the file directory (such as dir:. /production, so directly output to the production environment), of course, there are other properties, here is not introduced, please refer to the official website for details.
Let's take a look at the output process:
Finally, the Main-built.js file is generated, and then we try to replace the place where the original code was referenced,
<script data-main= "Main-built.js" src= "Static/scripts/src/vendor/require/require.js" ></script>
As a result, the page still can display normally, the module or normal load, and our JS reference becomes a, greatly reduced the number of requests, perfect!
Using R.js to package JS files