本地开发常用的npm命令

Published on
Published on
/2 mins read/---

将包链接到本地使用

cd ~/path/to/package
npm link

取消链接包

cd ~/path/to/package
npm unlink

从全局npm列表中移除

npm rm --global <package-name>

检查包是否被移除

npm list --global

清理 npx 缓存

rm -rf ~/.npm/_npx

执行包而不全局安装

npx <package-name>
# 添加@latest确保使用最新版本
npx <package-name>@latest

使用 NodeJSTypescriptesbuild 开发CLI的常用 package.json 配置

package.json
// ...
"scripts": {
  "dev": "tsc -w && npm run link",
  "start": "node dist/index.js",
  "build": "esbuild src/index.ts --bundle --platform=node --target=node18 --outfile=dist/index.js",
  "up": "npm run build && npm publish --access public && npm run unlink",
  "link": "npm unlink your-cli && npm i -g && chmod +x ./dist/index.js && npm link your-cli",
  "unlink": "npm rm -g your-cli && npm unlink your-cli"
},
"bin": {
  "your-cli": "./dist/index.js"
}
// 更多配置...

脚本说明

  • dev: 开发模式,监听TypeScript文件变化并自动链接
  • start: 运行构建后的入口文件
  • build: 使用esbuild打包TypeScript代码
  • up: 构建、发布包并取消本地链接
  • link: 创建全局链接供本地测试
  • unlink: 清理全局链接

其他有用的npm命令

查看包信息

npm info <package-name>
npm view <package-name> versions --json

更新依赖

npm update
npm outdated  # 查看过时的依赖

清理缓存

npm cache clean --force

安装特定版本

npm install <package-name>@<version>
npm install <package-name>@latest

检查全局安装的包

npm list --global --depth=0

Happy linking!