随着项目越来越复杂,功能越来越庞大,需要引入的公共数据也就越来越多,所以「模块」的解决方案应用而生。
//math.js
module.exports.add = (x, y) => x + y;
//program.js
var math = require(\\\'math\\\');
math.add(1,2)
define(id?, dependencies?, factory)
//定义模块 demo.js
define(function(){
var exports = {};
exports.sayHello = function(){
alert(\\\'Hello from module:\\\' + module.id)
}
return exports;
})
//使用
requite(\\\'demo\\\',function(demo){
demo.sayHello();
});
//模块 user.js
let name = \\\'cuishunbiao\\\';
let sex = \\\'男\\\';
let work = \\\'web\\\';
export {
name,
sex,
work
}
//main.js
import {name,sex,work} from \\\'./user.js\\\'
console.log(name,sex,work);
// lib.js
var counter = 1;
function addCounter(){
counter++
}
module.exports = {
counter: counter,
addCounter: addCounter
}
//main.js
var counter = require(\\\'./lib\\\').counter;
var addCounter = require(\\\'./lib\\\').addCounter;
console.log(counter);//1
addCounter();
console.log(counter);//1 输出值不受影响
//lib.js
export let counter = 1;
export function addCounter(){
counter++
}
//main.js
import {counter,addCounter} from \\\'./lib\\\';
console.log(counter);//1
addCounter();
console.log(counter);//2 改变了输出值
;(function (name, definition) {
// 检测上下文环境是否为AMD或CMD
var hasDefine = typeof define === \\\'function\\\',
// 检查上下文环境是否为Node
hasExports = typeof module !== \\\'undefined\\\' && module.exports;
if (hasDefine) {
// AMD环境或CMD环境
define(definition);
} else if (hasExports) {
// 定义为普通Node模块
module.exports = definition();
} else {
// 将模块的执行结果挂在window变量中,在浏览器中this指向window对象
this[name] = definition();
}
})(\\\'hello\\\', function () {
var hello = function () {};
return hello;
});
https://my.oschina.net/qufei1993/blog/4701150
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34590.html