CommonJS 模块用于在服务器环境中使用,而 Node.js 使用了 CommonJS 模块的轻微修改版本,本文就介绍这种 Node.js 风格的 CommonJS 模块。
模块就是以 .js
为扩展名的 JavaScript 文件。
1.导出
Node.js 通过将需要导出的模块成员赋值给 module.exports
来实现导出。
同一个模块中可以同时存在多个 module.exports = 值
,后定义的 module.exports = 值
会覆盖先定义的 module.exports = 值
。
//module.exports的类型
console.log(typeof module.exports); // "object"
//module.exports的默认值
console.log(module.exports); // {}
1.1导出一个对象字面量
module.exports
的值为一个对象字面量,对象字面量的属性为需要导出的模块成员。
//前缀方式(前面的module.可以省略,一般不推荐省略)
[module.]exports.成员名1 = 成员定义1;
[module.]exports.成员名2 = 成员定义2;
[module.]exports.成员名N = 成员定义N;
//末尾方式
成员定义1
成员定义2
成员定义N
module.exports = { 成员名1, 成员名2, 成员名N };
1.2导出一个模块成员
module.exports
的值为一个模块成员。
//前缀方式
module.exports = 成员定义;
//末尾方式
成员定义
module.exports = 成员名;
2.导入
require()
函数的返回值是 '模块标识符'
导出的模块成员。
//模块标识符格式
//绝对路径
require('/module.js');
//相对路径
require('./module.js');
require('../module.js');
//Node.js内置模块
require('node:http');
//npm包内模块
require('包名');
2.1返回值为一个对象字面量
//使用解构赋值只导入打算使用的模块成员
const { 成员名1, 成员名2, 成员名N } = require('模块标识符');
2.2返回值为一个模块成员
const 常量名 = require('模块标识符');
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/experience/javascriptexp/21371.html