common JSとAMDは簡単に原理を実現します.
2507 ワード
a.js内容:
(1)用法
(1)概要
module.exports= " ";
1、common JS(1)用法
CommonJS :{ (require)} { (exports)} { (module)}
require() ;exports , ;module 。
Node CommonJS , , 。
var math = require('math');
, :
var math = require('math');
math.add(2,3); // 5
(2)実現let fs = require('fs');
function req(moudleName) {
let content = fs.readFileSync(moudleName,'utf-8')
let fn = new Function('exports','module','__dirname','__filename',content + '
return module.exports');
let module ={
exports:{}
}
return fn(module.exports,module,req,__dirname,__filename)
}
let str = req("./a.js")
console.log(str);
2、AMD(requireJS)(1)概要
(1) js , ;
(2) , 。
:
async , 。IE , defer, defer 。
data-main , 。 , js main.js, require.js 。
require.js js, main.js main。
require.config({
'baseUrl': 'js', //
'paths': { // JS
jquery: 'libs/jquery-1.11.1.min',
underscore: 'libs/underscore-min',
backbone: 'libs/backbone-min',
},
'shim': //
{
backbone: {
'deps': ['jquery', 'underscore'],
'exports': 'Backbone'
},
underscore: {
'exports': '_'
},
},
urlArgs: "version=1.0" // , 304
});
(2) let factorys ={};
function define(moudleName,dependencies,factory){
factorys[moudleName] = factory;
factory.dependencies = dependencies; // 。
}
function require(mods,callback){
let result = mods.map(function(mod){ //name age
let factory = factorys[mod];
let exports;
let dependencies = factory.dependencies;// ,
require(dependencies,function(){
exports = factory.apply(null,arguments);
})
return exports;
});
callback.apply(null,result)
}
define("name",[],function(){
return "dong"
})
define("age",["name"],function(name){
return name+26
})
require(["age"],function(age){
console.log(age)})