nodejs學習02——模塊化

參考:

https://www.bilibili.com/video/BV1gM411W7ex/

視頻 模塊化部分

什麼是模塊化與模塊 ?

將一個複雜的程序文件依據一定規則(規範)拆分成多個文件的過程稱之爲 模塊化。
其中拆分出的 每個文件就是一個模塊 ,模塊的內部數據是私有的,不過模塊可以暴露內部數據以便其他模塊使用。

模塊化的一些好處:

  1. 防止命名衝突
  2. 高複用性
  3. 高維護性

類似,java的import 導包,或者C++ 的 include "name".

實例1

新建me.js

function fun01(){
	console.log('hello..');
}

function fun02(param){
	return param+" back";
}

module.exports=fun01;

新建index.js

const me = require('./me.js');
me();

結果:

暴露數據

模塊暴露數據的方式有兩種:

  1. module.exports = value
  2. exports.name = value

使用時有幾點注意:

  • module.exports 可以暴露 任意 數據。
  • 不能使用 exports = value 的形式暴露數據,模塊內部 module 與 exports 的隱式關係
    exports = module.exports = {} ,即:exports與module.exports都指向同一塊內存。
    require 返回的是目標模塊中 module.exports 的值
//me.js
module.exports="123";

//暴露數據
// module.exports = {
//   tiemo,
//   niejiao
// }

// exports 暴露數據
// exports.niejiao = niejiao;
// exports.tiemo = tiemo;

//1. module.exports 可以暴露`任意`數據
// module.exports = 'iloveyou';
// module.exports = 521;

//2. 不能使用 `exports = value`的形式暴露數據
// exports = 'iloveyou' // X

// exports = module.exports = {}
// console.log(module.exports);
// console.log(module.exports === exports);

//index.js
const me = require('./me.js');
console.log(me);
//123

實例2

me.js

function fun01(){
	console.log('hello..');
}

function fun02(s){
	return s + "0_0";
}

// 暴露多個
module.exports={
	fun01,
	fun02
};

index.js

//導入模塊
const me = require('./me.js');

console.log(me);//{ fun01: [Function: fun01], fun02: [Function: fun02] }

me.fun01();
console.log(me.fun02('Lee'));

結果:

導入(引入)模塊

在模塊中使用 require 傳入文件路徑即可引入文件
const test = require('./me.js');

require 使用的一些注意事項:

  1. 對於自己創建的模塊,導入時路徑建議寫 相對路徑 ,且不能省略 ./ 和 ../
  2. js 和 json 文件導入時可以不用寫後綴,c/c++編寫的 node 擴展文件也可以不寫後綴,但是一
    般用不到
  3. 如果導入其他類型的文件,會以 js 文件進行處理
  4. 如果導入的路徑是個文件夾,則會
    首先 檢測該文件夾下 package.json 文件中 main 屬性對應的文件,如果存在則導入,反之如果文件不存在會報錯。
    如果 main 屬性不存在,或者 package.json 不存在,則會嘗試導入文件夾下的 index.js 和
    index.json ,
    如果還是沒找到,就會報錯
  5. 導入 node.js 內置模塊時,直接 require 模塊的名字即可,無需加 ./ 和 ../
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章