初识~模块只加载和缓存一次amd:asynchronousmoduledefinition
1、依赖在先:加载所有依赖后注入依赖
//define、require都是先加载所有可以依赖于模块的//依赖于模块。 顺序是随机的,加载结束即可//例如a、b、b依赖于a,结果如果b先加载结束,凉凉//有shim选项似乎就可以解决。 我想知道我想知道因为我错过了这个时代,所以使用//ab.jsdefine(['a ',' b'],function(a ) a,b ) ) define定义模块,返回内容ab3360 ) a,a //main.jsrequire(['ab'],function ) ab ) {console.log ) ab ); ); CommonJS,
例如,NodeJS可以省略文件扩展名,并具有默认加载机制。 https://nodejs.org/API/modules.html # modules _ all _ together
1、同时加载
//src/a.jsconsole.log(1,' a.js ); //仅一次module.exports=function a () }; //默认为exports.name='a.js '; //导出多个//src/b.jsconsta=require('./a ' )的console.log(a ); const { name : aname }=require ('./a ' ); console.log(a,aName ); UMD :通用模块定义
AMD和CommonJS的混合
(function(window,factory ) if ) typeofexports==='object ' ) { module.exports=factory; //jquery } else if (type of define==' function ' define.amd ) define ) factory ); } else { window.jQuery=factory (; //jquery}}(this,function ) { const jQuery={}; 返回jquery; ); cmd :公共模块定义
1、依赖懒惰加载,用什么加载什么,很像CommonJS
2、同时加载
//require同步加载定义(function (require,exports,module ) consta=require('./a ' ) ); console.log(a ); let b=null; if (! a ) b=require('./b ' ) console.log(b ) b; } exports.ab={a,b}; module.exports=function () console.log,b ); (; );
ES6,更像优雅的CommonJS
1、导入必须支持导出(或者理解为有导入,必须有对应的导出) )。
//src/a.js//空文件,无缺省导出,//src/b.jsimport a from './a '; //therequestedmoduledoesnotprovideanexportnamed ' default ' import { name } from './a '; 使用//therequestedmoduledoesnotprovideanexportnamed ' name//babel时,每个文件都是一个对象//a={} //name=undefined 2
与const常数类似,但没有临时死区是因为被提升到了文件的顶部吧
if(1)//在文件的根部输入来自from './a.js '; //词法错误unexpected token { }//src/a.js console.log (1,' a.js ' ); exportdefaultfunction(} (); export const name='a.js '; //src/index.htmlconsole.log(a ); import a from './a.js '; console.log (! ' ); console.log(name; import {name} from './a.js '; //提升到文件顶a=空; //分配给常量变量Assignment to constant variable。
顺便说一下,require也支持CommonJS这样的写法。 看起来和CMD语法完全一样。 https://www.douban.com/note/283566440 /
但是,执行结果不同。 我觉得可能在requireJS内部事先对回调函数执行了toString ()、所有require )、
//如此定义(函数(require,exports,module ) ) console.log,requiremodule3360main ); varmod1=require('./mod1 ); mod1.hello (; varmod2=require('./mod2); mod2.hello (; return { hello : function () } { console.log (' hello main ); }; );