what
- CommenJs是同步加载(同AMD不同,AMD是异步加载)
- CommonJS模块是对象,是运行时加载,运行时才把模块挂载在exports之上(加载整个模块的所有),加载模块其实就是查找对象属性。(这个在下面的栗子上你会体会到哒)。
Use
define(function(require, exports, module) {
//Put traditional CommonJS module content here
});
可以看出有三个参数require、exports、module,这三个参数就是commenJs需要使用的。
- 导出使用
module.exports,也可以exports。就是在此对象上挂属性。exports指向module.exports,即exports= module.exports。 - 加载模块使用
require('xxx')。相对、绝对路径均可。默认引用js,可以不写.js后缀。
a.js
module.exports.add = function add(params) {
return ++params;
}
exports.sub = function sub(params) {
return --params;
}
index.html
var count= require('./a');
console.log(count.sub(1));
console.log(count.add(1))
还可以这么写!!!
function count() {
this.add = function(params){
++params;
},
this.sub = function(params){
--params
}
}
exports.count = count;
var count = require('./a').count;
var count = new count();
console.log(count.sub(1));
console.log(count.add(1));
- 消耗多重依赖
app.js
var modA = require( "./foo" );
var modB = require( "./bar" );
exports.app = function(){
console.log( "Im an application!" );
}
exports.foo = function(){
return modA.helloWorld();
}
bar.js
exports.name = "bar";
foo.js
require( "./bar" );
exports.helloWorld = function(){
return "Hello World!!"
}
报错 ERROE
但是吧,我现在用吧,老报错

然后吧,我就点进去他这个连接https://requirejs.org/docs/errors.html#notloaded我发现他这个这么说的:
If the error message includes Use require([]), then it was a top-level require call (not a require call inside a define() call) that should be using the async, callback version of require to load the code:
我一看,得了,就用AMD吧!!
*希望如果有大佬看见了,帮我解答一下啦~~~~*
UMD
- 是
AMD和CommonJS的糅合,跨平台的解决方案。 UMD先判断是否支持Node.js的模块(exports)是否存在,存在则使用Node.js模块模式。再判断是否支持AMD(define是否存在),存在则使用AMD方式加载模块。
define( function ( require, exports, module ){
var shuffler = require( "lib/shuffle" );
exports.randomize = function( input ){
return shuffler.shuffle( input );
}
});
(function ( root, factory ) {
if ( typeof exports === 'object' ) {
// CommonJS
factory( exports, require('b') );
} else if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define( ['exports', 'b'], factory);
} else {
// Browser globals
factory( (root.commonJsStrict = {}), root.b );
}
}(this, function ( exports, b ) {
//use b in some fashion.
// attach properties to the exports object to define
// the exported module properties.
exports.action = function () {};
}));
CMD
基本用法
define(function(require, exports, module) {
console.log('a.js执行');
console.log(require);
console.log(exports);
console.log(module);
})
- require, exports, module参数顺序不可乱
- 暴露api方法可以使用exports、module.exports、return
- 与requirejs不同的是,若是未暴露,则返回{},requirejs返回undefined
推荐阅读
嘻嘻嘻~~有几篇是我写的有几篇我局的不错的别人写de
ES6 Modelus
AMD
AMD , CMD, CommonJS,ES Module,UMD比较
javascript 设计模式 AMD CommonJS
requirejs.org

3151

被折叠的 条评论
为什么被折叠?



