记npm的常用命令和遇到的问题。

284 阅读2分钟

基础命令

# 查看 npm 的版本
npm -v

# 查看各个命令的简单用法
npm -l

# 查看 npm 命令列表
npm help

# 查看 npm 的配置
npm config list -l

国内镜像源

# npm 源
npm config set registry https://registry.npmjs.org/

# cnmp 源
npm config set registry https://registry.npmmirror.com/

# 淘宝源
npm config set registry https://registry.npm.taobao.org/

# 腾讯源
npm config set registry http://mirrors.cloud.tencent.com/npm/

# 验证
npm config get registry

初始化 package.json

npm init

# 跳过提问阶段
npm init -y

搜索模块

npm search <搜索词>

查看模块

npm list

安装模块

# 安装模块,并将其添加到 `dependencies` 中
npm install 包名
# 简写
npm i

# 安装指定版本
npm install 包名@0.0.1

# 安装 `react` 模块,并将其添加到 `peerDependencies` 中
npm install react --peer

# 安装 `react` 模块,并将其添加到 `devDependencies` 中
npm install react -D

卸载模块

npm uninstall 包名

更新模块

npm update 包名

执行脚本

package.json 的 scripts 字段,可以用于指定脚本命令,供 npm 直接调用。npm run 会创建一个 Shell,执行指定的命令。

npm run start

本地调试

# 将当前npm项目 npm-1 链接到全局
npm link
# 取消
npm unlink

# demo 项目 使用 npm-1
npm link npm-1
# 取消
npm unlink npm-1

遇到包更新后不生效,可以更新 version 版本,重新执行 npm link。

发布 npm

默认发布目录下所有文件

# 登录
npm login

## 注意,如果遇到网络不通登录不了,可通过设置代理
npm config set proxy http://127.0.0.1:7890

# 发布
npm publish

# .npmignore 下的文件不会发布

私域 npm 搭建

verdaccio

私域npm 包 指定 registry 地址

根目录 .npmrc 文件

@leslies/rc-component:registry=http://localhost:4873/

遇到问题

1. verdaccio搭建本地npm私库后,上传包到私库报错 503 Service Unavailable - PUT http://localhost:4873/@leslies%2fcss - one of the uplinks is down, refuse to publish

# 在verdaccio启动的配置文件config.yaml加上配置:
publish: 
    allow_offline: true

2. 遇到在项目中拉取 404

# 清除缓存再试
npm cache clean --force