首页 > 代码库 > JS模块化规范AMD之RequireJS

JS模块化规范AMD之RequireJS

 

1.基本操作

  1. 加载 JavaScript 文件(入口文件)

    RequireJS以一个相对于baseUrl的地址来加载所有的代码

    <script data-main="scripts/main.js" src="http://www.mamicode.com/scripts/require.js"></script>
    
  2. 相关配置

    requirejs.config({
    
        baseUrl: ‘js/lib‘,
    
        paths: {
            app: ‘../app‘
        }
    });
    
    requirejs([‘jquery‘, ‘canvas‘, ‘app/sub‘],
    function   ($,        canvas,   sub) {
        //jQuery, canvas and the app/sub module are all
        //loaded and can be used here now.
    });
    

2.模块相关

  1. 简单的值对

    define({
    
        color: "black",
        size: "unisize"
    });
    
  2. 没有任何依赖的函数式定义

    define(function () {
    
        return {
            color: "black",
            size: "unisize"
        }
    });
    
  3. 存在依赖的函数式定义

    define(["./cart", "./inventory"], function(cart, inventory) {
            //return an object to define the "my/shirt" module.
            return {
                color: "blue",
                size: "large",
                addToCart: function() {
                    inventory.decrement(this);
                    cart.add(this);
                }
            }
        }
    );
    

4.将模块定义为一个函数

    define(["my/cart", "my/inventory"],
        function(cart, inventory) {

            return function(title) {
                return title ? (window.title = title) :
                       inventory.storeName + ‘ ‘ + cart.name;
            }
        }
    );

3.简单包装CommonJS来定义模块

define(function(require, exports, module) {
    var a = require(‘a‘),
        b = require(‘b‘);

    //Return the module value
    return function () {};
    }
);

4. 定义一个命名模块(jquery中使用)

define("foo/title",
    ["my/cart", "my/inventory"],
    function(cart, inventory) {
        //Define foo/title object in here.
   }
);

jquery:

if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function() {
        return jQuery;
    } );
}

5.JSONP服务依赖

为了在RequireJS中使用JSON服务,须要将callback参数的值指定为"define"。这意味着你可将获取到的JSONP URL的值看成是一个模块定义。

下面是一个调用JSONP API端点的示例。该示例中,JSONP的callback参数为"callback",因此"callback=define"告诉API将JSON响应包裹到一个"define()"中:

require(["http://example.com/api/data.json?callback=define"],
    function (data) {
        //The data object will be the API response for the
        //JSONP data call.
        console.log(data);
    }
);

仅支持返回值类型为JSON object的JSONP服务,其他返回类型如数组、字串、数字等都不能支持。

6.压缩合并

  1. 常规压缩合并

    node r.js -o baseUrl=js name=main out=built.js
    

    有外部CDN的情况

    //表示paths.jquery不参与合并,压缩。这时生成的built.js
    node r.js -o baseUrl=js name=main out=built.js paths.jquery=empty:  也就不包含它了。
    

    合并成大文件,设置配置文件

    ({
        appDir: "./",
        baseUrl: "js",
        dir: "../r6-built",
        paths: {
            jquery: ‘empty:‘
        },
        modules: [
            {
                name: "page1"
            },
            {
                name: "page2"
            }
        ]
    })
    

    命令

    node r.js -o build.js
    
  2. 合并压缩CSS

    node r.js -o cssIn=css/main.css out=css/built.css
    

    还可以使用optimizeCss参数设置来配置是否压缩及压缩选项。

    optimizeCss的取值有

    none  不压缩,仅合并
    
    standard  标准压缩 去换行、空格、注释
    
    standard.keepLines  除标准压缩外,保留换行
    
    standard.keepComments  除标准压缩外,保留注释
    
    standard.keepComments.keepLines  除标准压缩外,保留换行和注释
    

    示例:

    node r.js -o cssIn=css/main.css out=css/built.css optimizeCss=standard
    

    压缩后built.css整个为一行了。

 

<style>body>*:first-child { margin-top: 0 !important } body>*:last-child { margin-bottom: 0 !important } p,blockquote,ul,ol,dl,table,pre { margin: 15px 0 } h1,h2,h3,h4,h5,h6 { padding: 0; font-weight: bold } h1 tt,h1 code,h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code { font-size: inherit } body>h2:first-child,body>h1:first-child,body>h1:first-child+h2,body>h3:first-child,body>h4:first-child,body>h5:first-child,body>h6:first-child { margin-top: 0; padding-top: 0 } a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6 { margin-top: 0; padding-top: 0 } h1+p,h2+p,h3+p,h4+p,h5+p,h6+p { margin-top: 10px } a { color: #4183C4; text-decoration: none } a:hover { text-decoration: underline } ul,ol { padding-left: 30px } ul li>:first-child,ol li>:first-child,ul li ul:first-of-type,ol li ol:first-of-type,ul li ol:first-of-type,ol li ul:first-of-type { margin-top: 0px } ul ul,ul ol,ol ol,ol ul { margin-bottom: 0 } dl { padding: 0 } dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px } dl dt:first-child { padding: 0 } dl dt>:first-child { margin-top: 0px } dl dt>:last-child { margin-bottom: 0px } dl dd { margin: 0 0 15px; padding: 0 15px } dl dd>:first-child { margin-top: 0px } dl dd>:last-child { margin-bottom: 0px } pre,code,tt { font-size: 12px; font-family: Consolas, "Liberation Mono", Courier, monospace } code,tt { margin: 0 0px; padding: 0px 0px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8 } pre>code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent } pre { background-color: #f8f8f8; border: 1px solid #ccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px } pre code,pre tt { background-color: transparent; border: none } kbd { background-color: #DDDDDD; background-image: linear-gradient(#F1F1F1, #DDDDDD); background-repeat: repeat-x; border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; border-style: solid; border-width: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 10px; padding: 1px 4px } blockquote { border-left: 4px solid #DDD; padding: 0 15px; color: #777 } blockquote>:first-child { margin-top: 0px } blockquote>:last-child { margin-bottom: 0px } hr { clear: both; margin: 15px 0; height: 0px; overflow: hidden; border: none; background: transparent; border-bottom: 4px solid #ddd; padding: 0 } .postBody a:link, .postBody a:visited, .postBody a:active ,.postBody a,.postBody a:hover, { text-decoration: none } a:hover { cursor: pointer } img { max-width: 100% }</style>

JS模块化规范AMD之RequireJS