RequireJS的使用步驟

這是我參與更文挑戰的第7天,活動詳情查看: 更文挑戰javascript


RequireJS的使用步驟

更多模塊化的知識,請參考前端視頻專題《前端爲何須要模塊化》css

第一步,下載RequireJS

下載過程略......前端

第二步,編寫模塊

//-----moduleA.js

define([],function(){
   //經過return輸出模塊A
	return {
		f1(){ ... },
 		f2(){ ... }
	}
})
複製代碼
//-----moduelB.js
//模塊B引用了模塊A

define(["moduleA"],function(ma){
	//參數ma就是模塊A,能夠直接使用
   return ...; //根據須要輸出B模塊
})
複製代碼
//-----moduleC.js
//模塊C引用了模塊B,和模塊jquery
define(["moduleB","jquery"],function(mb, $){
	//參數mb對應模塊B
	//參數$對應模塊jquery
   //數組中聲明的模塊會被自動注入到參數中,編寫時沒有前後順序
	return ...; //根據須要輸出模塊C
})
複製代碼

第三步,編寫配置文件

requirejs({
	baseUrl : "http://localhost:8000/myproject/",
	paths : {
		"vali" : "scripts/jquery.validate",
		"jquery" : "scripts/jquery-2.0.3",
		"swiper" : "scripts/swiper",
		"moduleA" : "mymodules/inputauto",
      "jq.cookie" : "scripts/jquery.cookie", //不符合AMD規範的JS
		"bootstrap" : "scripts/bootstrap" //不符合AMD規範的JS
	},
	shim : { //對於不符合AMD規範的模塊,須要使用shim配置
		"jq.cookie" : {
			deps : ["jquery"] //使用deps聲明該模塊依賴jquery
		},
		"bootstrap" : {
			deps : ["jquery"]
		}
	}
})
複製代碼

重要說明:java

AMD規範要求jquery

一個標準模塊必須使用define函數來定義bootstrap

就像上面的例子那樣。數組

對於不符合AMD規範的代碼,沒法被視爲一個標準的模塊markdown

這會帶來一個問題,那就是它沒法使用標準的方式來引入它須要的其它模塊,例如jquerycookie

因而纔有了shim配置app

它能夠有效的解決非規範模塊的依賴問題

例如 jquery.cookie.js 文件

$.extend({
	addCookie: function(){
		console.log("add cookie");
	},
	getCookie: function() {
		console.log("get cookie");
	},
	removeCookie : function(){
		console.log("remove cookie");
	}
})
複製代碼

因爲這個文件不符合AMD規範的寫法

這個文件實際上依賴了jquery

requireJS沒法管理它的依賴

若是不使用shim進行配置,將會出現找不到$的錯誤

第四步,編寫業務文件,使用這些模塊

//-----home.js

//加載配置文件,使其生效,注意配置文件的路徑要根據實際狀況編寫
require(["./conf/config.js"],function(){
	//加載全部你須要的模塊,模塊名稱須要跟配置文件中一致
	//數組中聲明的依賴模塊會被自動加載,並注入到對應的參數中
	require(["jquery","swiper","moduleA","jquery.cookie"], function($,Swiper,ma){
		//$對應jquery模塊,Swiper對應swiper模塊,ma對應moduleA模塊
		//因爲jquery.cookie模塊自己沒有輸出內容
 		//只是對jquery的擴展,所以不須要寫參數來接收

		//編寫正常的業務代碼
	})
})
複製代碼

第五步,頁面引入JS文件

img

到此爲止,基本就能夠使用了

不過在實戰當中,這顯然是不夠完美的

由於咱們的CSS尚未被模塊化

第六步,下載樣式處理文件css.js

該文件非官方提供,須要自行百度

或私聊我吧,這個沒辦法放到文章中

第七步,改造配置文件

requirejs({
	baseUrl : "http://localhost:8000/myproject/",
	paths : {
		"vali" : "scripts/jquery.validate",
		"jquery" : "scripts/jquery-2.0.3",
		"swiper" : "scripts/swiper",
		"moduleA" : "mymodules/inputauto",
		"jq.cookie" : "scripts/jquery.cookie",
		"bootstrap" : "scripts/bootstrap",
		"css" : "scripts/css" //處理CSS樣式的模塊
	},
	shim : {
		"jq.cookie" : {
			deps : ["jquery"]
		},
		"swiper" : {
			//css文件也能夠被當成模塊,直接聲明依賴,自動加載
			deps : ["css!styles/swiper.css"]
		},
		"bootstrap" : {
			deps : [
				"jquery",
				//css文件也能夠被當成模塊,直接聲明依賴,自動加載
				"css!styles/bootstrap.css"
			]
		}
	}
})
複製代碼

經過css.js的處理,一個JS模塊,能夠自動依賴對應的樣式文件

加載模塊時,將更加的省力、省心

require(["swiper"],function(Swiper){
	//除了swiper對應的js文件外
	//因爲以前作了shim配置,並聲明瞭css依賴
	//swiper.js和swiper.css將會被做爲一個總體一塊兒加載
	//真正作到了模塊化的思惟方式
})
複製代碼

第八步,完。

相關文章
相關標籤/搜索