Require. js: a deep understanding of require. js features

Source: Internet
Author: User

Require. js: a deep understanding of require. js features

Now, Require. js is my favorite Javascript programming method. It can reduce code to zero and facilitate management. The Require. js Optimizer can help us to scatter a large application into multiple small applications, connect them through dependencies, and finally combine them during compilation and packaging. These reasons prompted us to use require. js.

So, let's take a look at the awesome features of require. js!

Compatible with CommonJS

AMD (asynchronous module definition Specification) emerged from the CommonJS Working Group. CommonJS aims to create the Javascript ecosystem. One important part of CommonJS is transport/c, the predecessor of AMD, while require. js is an implementation of this specification.

The syntax difference between the CommonJS module and AMD module is mainly caused by AMD's need to support asynchronous features of browsers. The CommonJS module needs to be synchronized, for example:
Copy codeThe Code is as follows:
Var someModule = require ("someModule ");
Var anotherModule = require ("anotherModule ");
 
Exports. asplode = function (){
SomeModule. doTehAwesome ();
AnotherModule. doMoarAwesome ();
};
The AMD module asynchronously loads the module. Therefore, the module definition requires an array as the first parameter, and the callback function after the module is loaded is passed in as the second parameter.
Copy codeThe Code is as follows:
Define (["someModule"], function (someModule ){
Return {
Asplode: function (){
SomeModule. doTehAwesome ();
 
// This will be executed asynchronously
Require (["anotherModule"], function (anotherModule ){
AnotherModule. doMoarAwesome ();
});
}
};
});
However, AMD is also compatible with CommonJS syntax in require. js. Using AMD's define function to package the CommonJS module, you can also have a CommonJS module in AMD, for example:
Copy codeThe Code is as follows:
Define (function (require, exports, module)
Var someModule = require ("someModule ");
Var anotherModule = require ("anotherModule ");
 
SomeModule. doTehAwesome ();
AnotherModule. doMoarAwesome ();
 
Exports. asplode = function (){
SomeModule. doTehAwesome ();
AnotherModule. doMoarAwesome ();
};
});

In fact, require. js interprets the module content of the callback function through the function. toString, finds its correct dependency, and converts it into a common AMD module. Note that if you write a module in this way, it may be incompatible with other AMD loaders, because this violates AMD specifications, however, it can understand the format.

What happened here? require. js actually implements the function. toString callback function to parse the module content and find the correct dependency, just like it, if it is a normal AMD module. It is important to note that if you choose to write modules like this, they will most likely be incompatible with other AMD module loaders because this violates AMD specifications, but it is a good understanding that this format exists!

CDN rollback

Another hidden treasure of require. js is that it supports loading local libraries when the CDN Load is incorrect. We can achieve this through require. config:
Copy codeThe Code is as follows:
Requirejs. config ({
Paths :{
Jquery :[
'// Cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js ',
'Lib/jquery'
]
}
});

No dependency? Object literal volume? No problem!

When you write a module without any dependencies and only return an object containing some function functions, we can use a simple Syntax:
Copy codeThe Code is as follows:
Define ({
ForceChoke: function (){
 
},
ForceLighting: function (){
 
},
ForceRun: function (){
 
}
});
It is very simple and useful. If this module is only a set of functions or a data packet.

Circular dependency

In some cases, we may need functions in modules moduleA and moduleA to depend on some applications. This is circular dependency.
Copy codeThe Code is as follows:
// Js/app/moduleA. js
Define (["require", "app/app"],
Function (require, app ){
Return {
Foo: function (title ){
Var app = require ("app/app ");
Return app. something ();
}
}
}
);
Obtain the module address.

If you need to get the module address, you can do this ......
Copy codeThe Code is as follows:
Var path = require. toUrl ("./style.css ");

BaseUrl

Generally, during unit tests, your source code may be stored in a folder similar to src, and your tests may be stored in a folder similar to tests. This may be difficult to make the test configuration correct.

For example, we have an index.html file in the tests file and need to locally load tests/spec/*. js. Assume that all source code is in src/js/*. js, and there is a main. js in this folder.

In index.html, data-main is not set when require. js is loaded.
Copy codeThe Code is as follows:
<Script src = "src/js/vendor/require. js"> </script>
<Script>
Require (["../src/js/main. js"], function (){
Require. config ({
BaseUrl: "../src/js /"
});
 
Require ([
"./Spec/test. spec. js ",
"./Spec/moar. spec. js"
], Function (){
// Start your test framework
});
});
</Script>

You can find that main. js is loaded. However, since data-main is not set, we need to create a baseUrl for callback. When data-main is used, baseUrl is automatically set based on the files it sets.

Here, you can see that main. js is loaded. However, since it does not load the primary script tag of data, you must specify a base. When the data is mainly used for baseURL, It is inferred from the location in the main file. With the custom baseUrl, we can easily separate the test code from the application code.

JSONP

We can handle the JSONP terminal as follows:
Copy codeThe Code is as follows:
Require ([
"Http://someapi.com/foo? Callback = define"
], Function (data ){
Console. log (data );
});
Shim is used for non-AMD Databases

We need to use a non-AMD library for many requests. For example, Backbone and Underscore are not applicable to AMD standards. JQuery actually defines itself as a global variable named jQuery, so no need to do anything about jQuery.

Fortunately, we can use the shim configuration to solve this problem.
Copy codeThe Code is as follows:
Require. config ({
Paths :{
"Backbone": "vendor/backbone ",
"Underscore": "vendor/underscore"
},
Shim :{
"Backbone ":{
Deps: ["underscore"],
Exports: "Backbone"
},
"Underscore ":{
Exports :"_"
}
}
});


Front-end require js usage Problems

Obviously, the dependency file can only be loaded before the code is executed at the bottom. You can use require to load the code at the bottom, put the code after the dependent file, and put it in window. onload = function () {here}

This page require AC_RunActive Contentjs

Clear the temporary files and open the website again to see if the website script has encountered an error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.