包管理

npm

安装、脚本、镜像配置与发布常用命令。 — 共 15 条

共 15 条代码片段

A. 安装与依赖

安装依赖

npm install
npm i
npm ci          # 按 lockfile 干净安装(CI 推荐)

添加依赖

npm install lodash
npm install lodash --save
npm install -D typescript        # 开发依赖
npm install -g npm               # 全局安装

移除依赖

npm uninstall lodash
npm uninstall -D typescript
npm uninstall -g npm

更新依赖

npm update
npm update lodash
npm outdated
npx npm-check-updates -u         # 升级 package.json 版本号

查看依赖

npm list
npm list --depth=0
npm ls lodash
npm view lodash version

B. Scripts

运行脚本

npm run dev
npm run build
npm start                        # 等价 npm run start
npm test                         # 等价 npm run test
npm run lint -- --fix

package.json scripts 示例

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint .",
    "prepare": "husky"
  }
}

npx 临时执行

npx create-next-app@latest
npx eslint .
npx --yes cowsay hello

C. 配置与镜像

设置镜像源

npm config get registry
npm config set registry https://registry.npmmirror.com
npm config set registry https://registry.npmjs.org

# 临时使用
npm install --registry=https://registry.npmmirror.com

.npmrc 常用配置

registry=https://registry.npmmirror.com
save-exact=true
engine-strict=true
legacy-peer-deps=true

初始化项目

npm init -y
npm init @eslint/config

缓存清理

npm cache verify
npm cache clean --force

D. 发布

登录与发布

npm login
npm whoami
npm publish
npm publish --access public
npm unpublish pkg@1.0.0

版本号

npm version patch    # 1.0.0 -> 1.0.1
npm version minor    # 1.0.0 -> 1.1.0
npm version major    # 1.0.0 -> 2.0.0
npm version 1.2.3

打包预览

npm pack
npm pack --dry-run