node模块
- 在node中,模块被分成两种:核心模块(http模块、URL模块、FS模块)和自定义模块,也叫文件模块
- node 模块是 CommonJS的实现
- 自定义模块需要按照CommonJS的规范来定义
- 一个js文件就是一个模块
- 一个模块里面的变量、方法等默认是只能在本文件中被访问,只有导出后才能被其他模块访问
- 导出方法:
- 如果是把所有数据都写在了一个对象里面,那么就用module.exports=对象名,这样都出后就是把整个对象导出,不会产生新对象
- 如果是以多个方法、变量导出就使用exports.xxx = xxx
// 方式1
const request = {
get(){
console.log('发送get请求');
},
post(){
console.log('发送post请求');
}
}
module.exports = request;
// 方式2
function get(){
console.log('发送get请求');
}
function post(){
console.log('发送post请求');
}
exports.get = get;
exports.post = post;
-
导入方法:
- require(‘模块路径’)
- 在一个模块组中 如果不指定模块,就会默认导入index.js
- 在指定的node_modules 文件夹下存放 module可以不写 ./node_modules/
// 主调模块是app02.js
// 被调模块放在 node_modules文件夹下
const request= require('./node_modules/axios/index.js')
const request = require('./node_modules/axios')
const request = require('axios')
// 以上3种方式都有效
- 如果想修改一个module的默认打开文件,可以在终端 cd 到指定的module目录,输入 npm init --yes, 就会生成一个package.json配置文件
{
“name”: “db”,
“version”: “1.0.0”,
“main”: “db.js”,
“scripts”: {
“test”: “echo “Error: no test specified” && exit 1”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“description”: “”
}
修改 main的属性即可