標籤:parent 封裝 hid 載入 loaded oca optimize 選項 擷取
1.基本操作
-
載入 JavaScript 檔案(入口檔案)
RequireJS以一個相對於baseUrl的地址來載入所有的代碼
<script data-main="scripts/main.js" src="scripts/require.js"></script>
-
相關配置
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.模組相關
-
簡單的值對
define({ color: "black", size: "unisize"});
-
沒有任何依賴的函數式定義
define(function () { return { color: "black", size: "unisize" }});
-
存在依賴的函數式定義
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.壓縮合并
-
常規壓縮合并
node r.js -o baseUrl=js name=main out=built.js
有外部CDN的情況
//表示paths.jquery不參與合并,壓縮。這時產生的built.jsnode 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
-
合并壓縮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整個為一行了。
JS模組化規範AMD之RequireJS