Look at C1.js.
Run effect
Can see requirejs
help our home in all modules, we can better organize JavaScript code.
Optimized loadingAfter we have modularized the code, we do not want to increase the number of requests, which will slow down the performance of the Web page (this is asynchronous loading, but the browser has too many asynchronous requests or problems), so we want to merge the code.
Use r.js
:
node r.js -o build.js
Using R.js
Look at the results:
After building
After the build, our code has been processed.
Look at the running effect.
Reduction of requests
Can be seen by r.js
helping us refine the request (by merging the files).
How to configure
- Requirejs How to configure, we look at Common.js
requirejs.config({ baseUrl: ‘js/lib‘, 从这个位置加载模块 paths: { app: ‘../app‘ }, shim: { backbone: { deps: [‘jquery‘, ‘underscore‘], exports: ‘Backbone‘ }, underscore: { exports: ‘_‘ } }});
Properties |
meaning |
BaseUrl |
Where to load the module |
App: '.. /app ' |
Like this ' app/sub ', look for sub modules in the app directory |
Shim |
Globally exported libraries, packed here |
You can see the Chinese manual for a more detailed explanation.
- R.js How to configure, we look at Build.js
There is a full set of configuration instructions Example.build.js, how do we configure ourselves.
{appdir: '. /www ', Mainconfigfile: '. /www/js/common.js ', dir: '. /www-built ', modules: [//first set up the common build layer. {//module names is relative to BaseUrl name: '. /common ',//list common dependencies here. Only need to list//top level dependencies, "include" would find//nested dependencies. Include: [' jquery ', ' app/lib ', ' app/controller/base ', ' app/ Model/base ']},//now set up a build layer for each main layer, but exclude//the common One. "Exclude" would exclude nested//the nested, built dependencies from "common". Any//"exclude" so includes built modules should be//listed before the build layer that wants to exclude It. The "Page1" and "Page2" modules are **not** the targets of//the optimization, because Shim Config was in play, an Dshimmed dependencies need to maintain their load order. In this example, Common.js'll hold jquery, so backbone//needs to be delayed from loading until Common.js Finis Hes. That loading sequence was controlled in page1.html. {//module names is relative to baseurl/paths config name: ' app/main1 ', exclude: ['.. /common '}, {//module names is relative to BaseUrl name: ' App/main2 ', ex Clude: [' ... /common '}]}
We mainly look at modules
the following definition of the array, is actually a file dependency, R.js will use the relationship here, merge files. Detailed configuration meaning can be seen in the document
Tip: R.js can also optimize CSS.
How to DebugAfter the previous code has been optimized, debugging is painful, and here we can use Sourcemap technology to debug the optimized code. Do the following.
- Modify the Build.js to add the following configuration
generateSourceMaps: true,preserveLicenseComments: false,optimize: "uglify2",
- Re-build
node r.js -o build.js
Open Browser support
It is best to use the Firefox browser, chrome from the local file open HTML does not work properly sourcemap. Just use Firefox to browse it.
Firefox support Sourcemap
Can see the code can be loaded non-optimized, some people will ask, this do not request many times? Optimize one copy, not optimize it, so it's not worse. In fact, only when you debug, turn on this feature will request the corresponding Sourcemap file, so it is not wasted for users.
Write a server let chrome also support
Chrome itself is support for source map, that is, the right to open files directly from the hard disk permissions have special treatment. file://
many things can not be done with the path of the beginning. So let's do a simple server.
Add a server.js file under the Tools directory
var http = require (' http '), url = require (' URL '), Path = require (' path '), FS = require (' FS '), Port = PROCESS.A RGV[2] | | 8888, types = {' html ': ' text/html ', ' js ': ' Application/javascript '};http.createserver (function (requ EST, response) {var uri = Url.parse (request.url). Pathname, filename = path.join (__dirname, '.. ', URI); Console.log (filename); fs.exists (filename, function (exists) {if (!exists) {Response.writehead (404, {' Content-type ': ' TEXT/PL Ain '}); Response.Write (' 404 Not found\n '); Response.End (); Return } var type = Filename.split ('. '); Type = Type[type.length-1]; Response.writehead ($, {' Content-type ': types[type] + '; Charset=utf-8 '}); Fs.createreadstream (filename). pipe (response); });}). Listen (parseint (port)); Console.log (' Static file server running at\n = http://localhost: ' + port + '/\nctrl + C to Shutdown ');
Turn on Chrome support Sourcemap
Turn on Chrome supportUse node to start the server
Start node ServerDebugging in the browser
Chrome requires server support publishingThis article is in terms of modularity, and release does not matter, but all written here, the program to publish it, the back of this article to discuss the project, you can see how this article process improved.
There are just a few ways to publish this:
- Windows Server directly to the remote past, copy a bit better. The Web Deploy tool is also useful.
- Linux uses FTP to remote, then copy.
- Use Rsync.
Let's take a look at the third kind. We use R.js to optimize how to publish to the server later. We follow the method recommended by deployment-techniques this article to say. This method of publishing is presented under these considerations.
- The built code is not submitted to version control. The reason is mainly for good maintenance, the pre-submission build is easy to forget, and the submission of optimized code if the conflict is difficult to diff,merge.
- It is not good to generate the built code on the server using R.js, because R.js will delete the directory and recreate it, so if the project is large, there will be a lot of 404 errors in the service for some time.
So we figured out how to synchronize the folders with incremental updates. The main reliance on the rsync command.
It is recommended to use the Grunt tool to package and then run a command to sync the folder. Let's look at the code.
/** * Gruntfile.js */module.exports = function (grunt) {//Do grunt-related things in here var Requirejs = require (" Requirejs "), exec = require (" child_process "). Exec, fatal = grunt.fail.fatal, log = Grunt.log, VERBOSE = grunt.verbose, fs = require (' FS '), Json5 = Fs.readfilesync ("./build.js", ' UTF8 '), JSON5 = R Equire (' json5 '),//Your r.js build Configuration Buildconfigmain = Json5.parse (JSON5); Transfer the build folder to the right location on the server Grunt.registertask ("Transfer", "TRANSFE R the build folder to. /website/www-built and remove it, function () {var done = This.async (); Delete the build folder locally after transferring exec ("Rsync-rlv--delete--delete-after. /www-built. /WebSite && RM-RF. /www-built ", function (err, stdout, stderr) {if (err) {Fatal (" Pr Oblem WitH rsync: "+ err +" "+ stderr); } verbose.writeln (stdout); Log.ok ("Rsync complete."); Done (); }); } ); Build static assets using R.js grunt.registertask ("Build", "Run the R.js Build script", Functi On () {var-done = This.async (); Log.writeln ("Running build ..."); Requirejs.optimize (buildconfigmain, function (output) {Log.writeln (output); Log.ok ("Main build Complete."); Done (); }, function (err) {fatal ("Main Build Failure:" + err); }); This was run after the build completes Grunt.task.run (["Transfer"]); } );};
Run results
Can see a new website folder, and the built intermediate files to sync to this folder, and the website file is available on the remote server, is not very convenient?
Publish ResultsThe above changes can be downloaded from here, you can play with Requirejs-deploy-demo
SummarizeAs can be seen, through the require.js,r.js can be very good for the development of modular language, using Grunt,rsync, we can complete the build and release capabilities.
Shenyin
Links: http://www.jianshu.com/p/7186e5f2f341
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
JavaScript Modular-require.js,r.js and packaged publishing