Home > Web Front-end > JS Tutorial > body text

Require.js implements js modular management tutorial

高洛峰
Release: 2017-03-30 16:42:45
Original
1134 people have browsed it

What is Require.js

Require.js is an AMD-standard lightweight jsModularizationManagementframework. The latest version of require.js 2.1.11 is only 14.88K after compression. It can divide the js code into one Modules can be loaded asynchronously or dynamically, and the dependencies between modules can be clearly seen, thereby improving code quality, performance and maintainability. The author of Require.js is James Burke, the founder of the AMD specification.

What benefits can Require.js bring?

Below we can give a simple example to illustrate:

Usually our page structure is as follows

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>require</title>
   <script src="js/a.js"></script>
   <script src="js/b.js"></script>
   <script src="js/c.js"></script>
   <script src="js/d.js"></script>
   <script src="js/e.js"></script>
   <script src="js/f.js"></script>
   <script src="js/g.js"></script>
</head>
<body>
<p>require</p>
</body>
</html>
Copy after login

The code in a.js

alert("require");
Copy after login

When running the page, you can find When the alert pops up, you need to click OK to display the content of p. Because the js of the page is rendered synchronously, the rendering of js will inevitably block the subsequent html rendering. Furthermore, introducing a lot of js files is not beautiful, but using require.js can achieve modular asynchronous loading of js.

How to use Require.js

First go to the require.js official website to download the latest version, and then introduce it to the page, as follows:

<script src="js/require.js" data-main="js/main.js"></script>
Copy after login

data-mainAttributecannot be ignored, the file pointed to by data-main is the file where the main code is located , the scripts configured in main.js will be loaded asynchronously, and the directory where main.js is located defaults to the root path.

require.js config

config method is used to configure running parameters. First set the parameters, see the example below:
My project file structure is as follows

Require.js implements js modular management tutorial

The main file main.js

require.config({
    baseUrl: "js",
    paths: {
        "jquery": ["lib/jquery-1.8.3.min"],
        "popup": ["lib/popup"],
        "moduleA": ["app/moduleA"],
        "moduleB": ["appmoduleB"]
    },
    shim: {
        &#39;popup&#39;: {
            deps: [&#39;jquery&#39;]
        }
    }
});
Copy after login

The config method receives an objectparameter. The following explains the role of each attribute.
baseUrl: Set the root path. If this attribute is not set, it will default to the directory where the main file is located. Here, set the JS directory as the root path.
paths: Set the alias and path of each module. Alias ​​must be used when calling the module. The resource file path can be a local path, or an external link, or multiple paths can be set. The path can be a stringpath, or an array. When there are two or more paths, it must be array.
Take the JQ path as an example, a single path "jquery": ["lib/jquery-1.8.3.min"]
Multiple paths "jquery": ["http://apps.bdimg.com/libs/jquery/ 1.8.3/jquery.min.js","lib/jquery-1.8.3.min"], when there are multiple paths, the resource file of the first path will be obtained first. If the first path fails to load, the second path will be loaded. path (Note: In my practice, when the first path uses CDN, the IE browser below IE11 will fail to load and no local resources will be called, the reason is unknown)
shim: Non-AMD standard modules cannot be called directly, this attribute Used to set non-AMD standard modules. The attribute value is an object. The pop-up plug-in I wrote is not AMD standard, so it needs to be set. The set module name and the module name it depends on must be the alias defined by the module in paths. deps is used to set the dependencies of this module. The popup plug-in depends on JQ

define(name,deps,callback)函数

单从语义就应该猜到这个函数用来定于模块,下面解释define函数,若看不懂别着急,后面会举例。
在require.js源码中可以看到有这么一行代码define = function (name, deps, callback) {} ,可知define接收三个参数
name:为可选参数,该模块的标识,字符串类型,通俗来讲就是给该模块取的名称,可自定义,但不能与其他模块名称相同,如果该参数未选,那么该模块的名称为该文件在paths中定义的别名
deps:当前模块的依赖,数组类型,为已定义的模块名称,若不存在依赖该参数可不填
callback:是一个函数或者对象,为函数时,当依赖的模块加载完成后该回调函数将被调用,依赖关系会以参数的形式注入到该函数上,参数与依赖的模块一一对应,(注:如果定义的模块想被其他模块引用需返回一个对象)。

通过define定义模块的方式可分为以下两类。

1. 无依赖模块
也就是说该模块无需依赖其他模块,可以直接定义,如下:

define({
    fnMethod: function() {
        return ("这是一个无依赖模块")
    }
});
Copy after login

该模块只传了一个对象类型的callback,也等价于

define(function() {
    return {
        fnMethod: function () {
            return ("这是一个无依赖模块")
        }
    }
});
Copy after login

该模块则传了一个函数类型的callback,模块定义了一个函数fnMethod,返回一个字符串值,实际上返回值也可以是其他类型,第二种方法只是将函数做为对象返回,建议采用第二种方法来定义无依赖模块。

2. 有依赖模块
定义有依赖模块格式需要稍作改变,格式如下:

 //假如moduleA模块返回了一个属性name,值为“老宋”,<p class="text">老马</p>

 define(["jquery","moduleA"],function($, mA) {    //参数和依赖的模块需一一对应
        return {
            fnMethod: function () {    
                return ($.text(".text") + mA.name);
            }
        }
    });
Copy after login

该例子表明当前模块依赖于jquery和moduleA,返回一个结果“老马老宋”。沿用上面的例子再举一个完整的例子:

 define("module",["jquery","moduleA"],function($, mA) {    //参数和依赖的模块需一一对应
        return {
            fnMethod: function () {    //fnMethod即提供给外部调用的接口
                return ($(".text").text() + mA.name);
            }
        }
 });
Copy after login

这里定义了一个名为module的模块,并且它依赖于jquery和moduleA模块。

当依赖的模块很多的时候再像下面这样写感觉是不是很挫?

define("module", ["jquery", "moduleA", "moduleB", "moduleC", "moduleD", "moduleE", "moduleF"], function ($, mA, mB, mC, mD, mE, mF) {
    return {
        fnMethod: function () {
            return ($(".text").text() + mA.name);
        }
    }
});
Copy after login

require.js2.0版本之后提供了一种更好的写法。

   define("module", function (require) {    //将“require”本身做为一个依赖注入到模块
    var $ = require("jquery"),
        mA = require("moduleA"),
        mB = require("moduleB"),
        mC = require("moduleC"),
        mD = require("moduleD"),
        mE = require("moduleE"),
        mF = require("moduleF");
    
    return {
        fnMethod: function () {
            return ($(".text").text() + mA.name);
        }
    }
});
Copy after login

 以上就是Require.js实现js模块化管理教程的内容,更多相关内容请关注PHP中文网(www.php.cn)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!