npm (Node Package Manager) 是 Node.js 的官方包管理工具,提供:
# 通过官方安装包
https://nodejs.org
# 验证安装
node -v
npm -v
npm init # 交互式创建package.json
npm init -y # 快速生成默认配置
npm config set registry https://registry.npmmirror.com # 阿里云镜像
npm config get registry # 查看当前源
npm config delete registry # 恢复默认源
npm install # 安装所有依赖
npm install lodash # 安装生产依赖
npm install eslint -D # 安装开发依赖
npm install [email protected] # 安装指定版本
npm install ../my-package # 安装本地包
npm uninstall axios # 卸载包
npm update # 更新所有依赖
npm outdated # 检查过时依赖
npm ls # 查看依赖树
npm cache clean --force # 清理缓存
{
"dependencies": { // 生产环境依赖
"lodash": "^4.17.21"
},
"devDependencies": { // 开发环境依赖
"webpack": "^5.75.0"
},
"peerDependencies": { // 宿主环境依赖
"react": ">=16.8.0"
},
"optionalDependencies": { // 可选依赖
"fsevents": "^2.3.2"
}
}
npm install -g typescript # 全局安装
npm list -g --depth=0 # 查看全局安装包
^1.2.3 # 兼容次要版本和补丁 (1.x.x)
~1.2.3 # 仅兼容补丁版本 (1.2.x)
1.2.x # 指定次要版本
* # 最新版本
npm shrinkwrap # 生成npm-shrinkwrap.json
npm ci # 严格按lockfile安装
{
"scripts": {
"start": "node index.js",
"test": "jest",
"build": "webpack --mode production",
"prepublish": "npm run build"
}
}
npm run test -- --coverage # 传递参数
npm run lint & npm run build # 并行执行
npm run prestart # 生命周期钩子
npm login # 登录账号
npm publish # 发布公开包
npm publish --access public # 明确发布公开包
npm version patch # 版本号升级
npm deprecate <pkg>@<version> "message" # 标记弃用
npm init --scope=yourorg # 创建组织包
npm publish --access restricted # 发布私有包
npm audit # 安全审计
npm audit fix # 自动修复漏洞
npm fund # 查看依赖资金信息
npm view react # 查看包信息
npm docs lodash # 打开文档网站
npm repo webpack # 打开源码仓库
npm explore react -- npm ls # 进入包目录
.npmrc 优先级:
项目级 > 用户级 > 全局 > npm内置
npm config set save-exact true # 精确版本
npm config set script-shell bash # 指定脚本shell
npm config set engine-strict true # 严格引擎检查
npm ci
代替 npm install
在CI环境npm outdated
和 npm update
package-lock.json
到版本控制npm audit
进行安全审计bin
字段.npmignore
控制发布内容peerDependencies
避免重复依赖@org/package
)# 解决方案:
sudo chown -R $(whoami) ~/.npm
# 或使用Node版本管理工具(nvm)
npm ls <package-name> # 查看依赖路径
npm dedupe # 尝试优化依赖树
npm install --prefer-offline # 优先使用缓存
npm config set prefer-offline true # 永久设置
转载吱一声~