【js模块化demo】CommonJS
CommonJs运行方式示例:CommonJS间接为前端模块,提供了后端脚本的模块化支持。
示例一:两个函数模块化成一个。
示例二:前端运行后端模块化脚本。
返回demo列表页
demo 代码分析
a.js
/**
* @author: cuixiaohuan
* Date: 15/12/7
* Time: 下午8:09
*/
module.exports = function () {
console.log('This is a.js');
};
b.js
/**
* @author: cuixiaohuan
* Date: 15/12/7
* Time: 下午8:09
*/
var a = require('./a');
a();
console.log('This is b.js');
node生成运行模块和输出如下
cuihuan:js_module_CommomJs cuixiaohuan$ browserify b.js -o b_brow.js
cuihuan:js_module_CommomJs cuixiaohuan$ node b_brow.js
This is a.js
This is b.js
生成的b_brow.js
/**
* @author: cuixiaohuan
* Date: 15/12/7
* Time: 下午8:09
*/
module.exports = function () {
console.log('This is a.js');
};
},{}],2:[function(require,module,exports){
/**
* @author: cuixiaohuan
* Date: 15/12/7
* Time: 下午8:09
*/
var a = require('./a');
a();
console.log('This is b.js');
},{"./a":1}]},{},[2]);
再来一个node的小栗子
# c.js
var uniq = require('uniq');
var nums = [ 5, 2, 1, 3, 2, 5, 4, 2, 0, 1 ];
console.log(uniq(nums));
# 生成node模块
$ browserify c.js > c_brew.js
#可以直接引入运行后端的函数