Previous:JS Modular Tool RequireJS Tutorial (1): First Look at RequireJSWe introduced RequireJS in a very simple way. This article will cover some basic knowledge of RequireJS, including API usage, etc.
Basic API
require defines three variables: define, require, requirejs. Among them, require === requirejs, and it is generally shorter to use require.
- define: As the name suggests, this API is used to define a module.
- require: Loads dependent modules and executes the callback function after loading.
a.js from the previous article:
define(function(){
function fun1(){
alert("it works");
}
fun1();
})
A module is defined via the define function, and then used in the page:
require(["js/a"]);
to load the module (Note that the dependencies in require are an array. Even if there is only one dependency, you must define it using an array.), the second parameter of the require API is callback, a function used to handle the logic after loading, such as:
require(["js/a"],function(){
alert("load finished");
})
Loading Files
In the previous examples, the loaded modules were all local JS files. However, in most cases, the JS that a webpage needs to load may come from a local server, other websites, or a CDN, so it cannot be loaded this way. Let's take loading a jQuery library as an example:
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery"]
}
})
require(["jquery","js/a"],function($){
$(function(){
alert("load finished");
})
})
This involvesrequire.config,require.configis used to configure the module loading location. Simply put, it gives a module a shorter and easier-to-remember name. For example, mark Baidu's jQuery library address asjquery, so when calling require, you only need to write["jquery"]to load that JS. We can configure local JS files in the same way:
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery"],
"a" : "js/a"
}
})
require(["jquery","a"],function($){
$(function(){
alert("load finished");
})
})
Configuring paths makes our module names more concise. paths also has an important feature: you can configure multiple paths. If the remote CDN library fails to load, a local library can be loaded, e.g.:
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],
"a" : "js/a"
}
})
require(["jquery","a"],function($){
$(function(){
alert("load finished");
})
})
With this configuration, if Baidu's jQuery fails to load, the jQuery in the local js directory will be loaded.
- When using RequireJS, you don't need to write
.jsas the suffix. Of course, you are also not allowed to write the suffix. - In the callback function in the example above, you can see
$parameter. This is the dependentjquerymodule's output variable. If you depend on multiple modules, you can write multiple parameters in order to use them:
require(["jquery","underscore"],function($, _){
$(function(){
_.each([1,2,3],alert);
})
})
If a module does not output a variable value, then there is no corresponding parameter. Therefore, try to write modules that output a value first, to prevent confusion caused by mismatched positions.
Global Configuration
In the above examples, the configuration appears repeatedly.require.configIf you add the configuration to every page, it will inevitably look inelegant. RequireJS provides a feature called "main data". We first create a main.js:
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],
"a" : "js/a"
}
})
Then use the following method in the page to use RequireJS:
<script data-main="js/main" src="js/require.js.html"></script>
Let me explain: the script tag loading the RequireJS script has added thedata-mainattribute. The JS specified by this attribute will be processed after require.js is loaded. We add therequire.configconfiguration todata-main, so that every page can use this configuration. Then the page can directly userequireto load all short module names.
data-mainThere is another important feature: when the script tag specifies the data-main attribute, require will by default use the JS specified by data-main as the root path. What does that mean? As in the abovedata-main="js/main"after setting, when we userequire(['jquery'])(without configuring jQuery's paths), require will automatically load the file js/jquery.js instead of jquery.js, which is equivalent to the default configuration:
require.config({
baseUrl : "js"
})
Third-Party Modules
Throughrequireloaded modules generally need to conform to the AMD specification, i.e., usedefineto declare modules. However, sometimes we need to load JS that does not follow the AMD specification. In such cases, we need another feature: shim. shim is also a bit difficult to explain. shim is directly translated as "pad", and it does have this meaning. Currently I mainly use it in two places.
1. Non-AMD module output: shim non-standard AMD modules into usable modules. For example, in older versions of jQuery, the AMD specification was not inherited, so you cannot directly require["jquery"]. In this case, shim is needed. For example, if I want to use the Underscore library, but it does not implement the AMD specification, we can configure it like this:
require.config({
shim: {
"underscore" : {
exports : "_";
}
}
})
After this configuration, we can reference the Underscore module in other modules:
require(["underscore"], function(_){
_.each([1,2,3], alert);
})
- Non-AMD modules in plugin form: we often use jQuery plugins, and these plugins basically do not conform to the AMD specification, such as the jquery.form plugin. In this case, we need to shim the form plugin into jQuery:
require.config({
shim: {
"underscore" : {
exports : "_";
},
"jquery.form" : {
deps : ["jquery"]
}
}
})
It can also be abbreviated as:
require.config({
shim: {
"underscore" : {
exports : "_";
},
"jquery.form" : ["jquery"]
}
})
After this configuration, we can use jQuery with the plugin loaded.
require.config(["jquery", "jquery.form"], function($){
$(function(){
$("#form").ajaxSubmit({...});
})
})
Alright, that's roughly all the basic configuration for RequireJS. There are some expanded features that will be mentioned in later articles.
Article source: https://github.com/liuxey/blog/issues/2