模塊
在nodeJS中一個(gè)文件就是一個(gè)模塊,這個(gè)模塊本質(zhì)就是一個(gè)函數(shù)
模塊化
CommonJs exports(導(dǎo)出) require(導(dǎo)入)
es6 export(導(dǎo)出) import(導(dǎo)入)
AMD define(導(dǎo)出) require(導(dǎo)入)
模塊的定義
module.exports,在module.exports對(duì)象上添加屬性導(dǎo)出值
exports,在exports對(duì)象上添加屬性導(dǎo)出值
exports對(duì)象和module.exports是同一個(gè)對(duì)象
exports對(duì)象添加屬性來導(dǎo)出值
module.exports對(duì)象可以賦值一個(gè)對(duì)象導(dǎo)出值
導(dǎo)出的始終是module.exports指向的對(duì)象
模塊引用
rquire("文件名"),執(zhí)行對(duì)應(yīng)的文件并返回該文件對(duì)象的module.exports對(duì)象
module.exports是什么
新建module_001.js
console.log(module);
node輸出
Module {
id: '.',
exports: {},
parent: null,
filename: 'F:\\work\\layUiDemo\\server\\module_001.js',
loaded: false,
children: [],
paths:
[ 'F:\\work\\layUiDemo\\server\\node_modules',
'F:\\work\\layUiDemo\\node_modules',
'F:\\work\\node_modules',
'F:\\node_modules' ] }
可以看到module是一個(gè)對(duì)象,module里面有exports對(duì)象
那么module.exports 跟exports有什么關(guān)系呢?
修改module_001.js
console.log(module.exports === exports); //輸出true 說明他們兩個(gè)指向同一個(gè)對(duì)象
module.exports 與 exports 的區(qū)別
新建module_001.js 和 module_002.js
module_001.js
let str = 'Hello';
let obj = {
name:'tom',
age:'18'
};
let fn = ()=>{
console.log('fn.........')
}
module.exports.str=str;
exports.obj = obj;
exports.fn = fn;
module_002.js
const allObj = require('./module_001');
console.log(allObj)
輸出
{ str: 'Hello',
obj: { name: 'tom', age: '18' },
fn: [Function: fn] }
前面我們說了module.exports 與exports 他們兩個(gè)指向同一個(gè)對(duì)象
現(xiàn)在我們改變module_001.js
let str = 'Hello';
let obj = {
name:'tom',
age:'18'
};
let fn = ()=>{
console.log('fn.........')
}
exports = {
str,
obj,
fn
}
輸出是空,我們把exports換成module.exports發(fā)現(xiàn)輸出就正常了。其原因在于,一開始module.exports 與 exports指向同一個(gè)對(duì)象,當(dāng)exports = {} 的時(shí)候 就改變了exports的指向。require() 方法返回的是module.exports