Nodejs学习02——模块化

发布时间 2023-11-09 17:52:42作者: htj10

参考:

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 模块的名字即可,无需加 ./ 和 ../