本節將簡述RequireJS經常使用的功能javascript
RequireJS 實現了 Asynchronous Module API.css
目錄:java
Nuget:Install-Package RequireJS(會包含2個文件.r.js是用來經過nodejs壓縮js的)node
<script src="scripts/require.js" defer async="true"></script>jquery
<script src="scripts/require.js" data-main="scripts/main"></script> git
包括baseUrl,paths,shim,map,enforceDefinegithub
<script data-main="main" src="Scripts/require.js"></script>api
require.config({ baseUrl: 'Scripts', paths: { jquery: ['//cdn.bootcss.com/jquery/2.2.3/jquery', 'jquery-2.2.4'] } }); require(['jquery'], function (a) { alert(a.fn.jquery); });
定義1個Cache模塊,緩存頁面中的js對象.緩存
define(['jquery'], function ($) { var cache = {}; return { set: function (key, val) { cache[key] = val; }, get: function (key) { return cache[key]; } } });
main.js異步
require(['cache'], function (cache) { alert(jQuery.fn.jquery); cache.set('a', 'hello'); }); require(['cache'], function (cache) { alert(cache.get('a')); });
不少js庫 並無支持AMD方式的模塊化開發.
本例子實現上面的cache功能
定義cached.js
var cache = { data: {}, set: function (key, val) { this.data[key] = val; }, get: function (key) { return this.data[key]; } };
main.js
require.config({ baseUrl: 'Scripts', paths: { jquery: ['//cdn.bootcss.com/jquery/2.2.3/jquery', 'jquery-2.2.4'] }, shim: { cached: { exports: 'cache', deps: ['jquery'] } } }); require(['cached'], function (cache) { cache.set('a', 'hello'); }); require(['cached'], function (cache) { alert(cache.get('a')); });
咱們的項目若是使用新版本js功能,但又不能直接替換老版本的js.多個版本共存的時候.
使用map函數
requirejs.config({ map: { '*': { 'jquery': 'scripts/jquery-2.2.4' }, 'scripts/cache': { 'jquery': '//cdn.bootcss.com/jquery/2.2.3/jquery.js' } } }); require(['scripts/cache'], function (a) { alert($.fn.jquery); });
map定義了2種jquery版本
*表示默認狀況下的jquery模塊使用本地2.2.4
scripts/cache表示模塊名爲此的時候,jquery使用遠程庫.遠程庫需添加js擴展名.
https://github.com/requirejs/requirejs/wiki/Plugins
AMD(中文版):
https://github.com/amdjs/amdjs-api/wiki/AMD-(%E4%B8%AD%E6%96%87%E7%89%88)