为什么引入模块化?
- 恼人的命名冲突
- 烦琐的文件依赖
- 加载顺序控制
js模块化解决了什么问题?
- 实现js的异步加载,避免网页失去响应
- 管理模块间的依赖,便于代码的编写与维护
怎么实现js模板化?(实现方案&how to coding)
demoRequireMoudle目录:
/js/app/demo.js
/lib/require.js
/lib/jquery.min.js
config.js
index.html
1.加载require.js
or
2.配置config.js
/*模板*/
require.config {
baseUrl: \' \',
paths: {
\' \': \' \', /*不用加js,因requirejs默认以.js结尾*/
\' \': \' \',
......
}
}
/*config.js*/
require.config {
baseUrl: \'./\',
paths: {
\'jquery\': \'lib/jquery.min\',
\'demo\': \'js/app/demo\'
}
}
require([\'demo\']) /*入口文件,数组的形式([\'array1\',\'array2\',\'...\'])*/
/*之后在index.html中添加*/
3.编写js模块
/*模板(我也不知道为啥 ^_^)*/
define(function(require) {
// The module code goes here
//遵循AMD规范
})
/*还有一种写法,但是不推荐这种写法。*/
define(funciton(require, exports, module) {
// The module code goes here
//这是seajs 的一种写法,可以参看seajs文档。
//不推荐这种写法。遵循CMD规范
})
/*demo.js*/
define(function(require) {
var $ = require(\'jquery\')
$(document.body).html(Because I like, so reluctantly, not so much why.
)
})
结束语:为了督促自己学习,在往后学习中会不断更新,纠正。文中肯定有不足之处,还读者请斧正^_^。
参考文章:
- Javascript模块化编程(一):模块的写法
- Seajs文档