模块的分类(自定义模块,内置模块,第三方模块),npm使用

本文介绍了模块的三种类型:自定义模块、内置模块和第三方模块,并详细讲解了npm的使用,包括创建package.json,安装、使用及管理依赖,以及配置npm源。

模块的分类

  • 自定义模块
    // 1. 创建模块
const name = { 
  id: 1,
  name: 'Yan'
}
const str = 'sdaf'

// 2. 导出模块

// module.exports = name   只能导出一个

module.exports = { // 批量导出
  name,
  str
}

// 模块的导入

// const { name,str } = require(路径)
const { name,str } = require('./name.js')
console.log( name.name , str )
  • 内置模块
	const process = require('process')
	const path = require('path')
	console.log(process.version)
	console.log(path.resolve('../'))
  • 案例: 打包压缩包
    • 流程:
      1. 读取文件
      2. 创建压缩包
      3. 将读取的数据流写入压缩包
      4. 输出压缩包
const fs = require('fs') // 读取yyb.txt文件

  const zlib = require('zlib') // 创建压缩包

  // const inp = fs.createReadStream( 路径 )
  const inp = fs.createReadStream( './yyb.txt' ) //读出数据

  const gzip = zlib.createGzip()  // 创建压缩包

  // const outp = fs.createWriteStream(路径)
  const outp = fs.createWriteStream( './yyb.txt.gz' )//输出压缩包

  inp 
    .pipe( gzip )
    .pipe( outp )
  • 第三方模块
    我一般都是从npmjs.com这个网站拉取
    使用流程:
    1. 安装
    先创建package.json 文件 (npm init -y)
    npm/cnpm i request -S/-D (安装 request)
    -S --save 生产环境
    -D --save-dev dev development的简写 开发环境
    2. 使用
    request 这个模块是做数据请求
    const request=require("request");
	console.log(request)
	request.get('http://api.douban.com/v2/movie/in_theaters', (err, response, body) => {
	  if (!err) {
	    // console.log(body);
	    console.log(JSON.parse(body))
	  } else {
	    console.log(err);
	  }
	})

npm 使用入门

官网:https://www.npmjs.com/

安装:无需安装

查看当前版本:

 $ npm -v

更新:

 $ npm install npm@latest -g

初始化工程

 $ npm init

 $ npm init --yes 默认配置

安装包

使用npm install会读取package.json文件来安装模块。安装的模块分为两类
dependencies和devDependencies,分别对应生产环境需要的安装包和开发环境需要的安装包。

 $ npm install

 $ npm install <package_name> 

 $ npm install <package_name> --save

 $ npm install <package_name> --save-dev

更新模块

 $ npm update

卸载模块

 $ npm uninstall <package_name>

 $ npm uninstall --save lodash

配置npm源

  • 临时使用, 安装包的时候通过–registry参数即可

    $ npm install express --registry https://registry.npm.taobao.org

  • 全局使用

      $ npm config set registry https://registry.npm.taobao.org
      // 配置后可通过下面方式来验证是否成功
      npm config get registry
      // 或
      npm info express
    
  • cnpm 使用

    	 // 安装cnpm
    	  npm install -g cnpm --registry=https://registry.npm.taobao.org
    
    	  // 使用cnpm安装包
    	  cnpm install express
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值