{T}

全局模块

全局模块是指安装在系统全局位置的 npm 包,可以在任何地方通过命令行直接使用,而不需要在每个项目中单独安装。本文档将全面介绍全局模块的管理、使用和最佳实践。

全局模块概述

全局模块 vs 本地模块

特性全局模块本地模块
安装位置系统全局目录项目的 node_modules
使用范围所有项目当前项目
版本管理单一版本每个项目独立版本
团队协作不易同步通过 package.json 同步
适用场景CLI 工具、脚手架项目依赖、库
更新策略手动更新通过 package.json 管理

典型应用场景

✅ 适合全局安装

  • 命令行工具(nodemon, pm2, http-server)
  • 脚手架工具(create-react-app, @vue/cli)
  • 代码质量工具(eslint, prettier)
  • 开发服务器(live-server, browser-sync)

❌ 不适合全局安装

  • 项目运行时依赖(express, lodash)
  • 构建工具(webpack, rollup)- 推荐本地安装
  • 测试框架(jest, mocha)- 推荐本地安装
  • UI 框架(react, vue)- 必须本地安装

安装与管理

全局模块安装位置

macOS/Linux

bash
# 查看全局模块安装路径
npm root -g

# 默认路径
/usr/local/lib/node_modules

# 查看全局命令安装路径
npm bin -g
# 默认:/usr/local/bin

# 查看全局配置
npm config get prefix
# 默认:/usr/local

目录结构

code
/usr/local/
├── bin/                    # 全局命令(符号链接)
│   ├── nodemon -> ../lib/node_modules/nodemon/bin/nodemon.js
│   ├── pm2 -> ../lib/node_modules/pm2/bin/pm2
│   └── ...
└── lib/
    └── node_modules/       # 全局模块实际安装位置
        ├── nodemon/
        ├── pm2/
        └── ...

Windows

bash
# 查看全局模块安装路径
npm root -g

# 默认路径
C:\Users\<username>\AppData\Roaming\npm\node_modules

# 查看全局命令安装路径
npm bin -g
# 默认:C:\Users\<username>\AppData\Roaming\npm

# 查看全局配置
npm config get prefix
# 默认:C:\Users\<username>\AppData\Roaming\npm

目录结构

code
C:\Users\<username>\AppData\Roaming\npm\
├── nodemon.cmd            # Windows 批处理文件
├── pm2.cmd
├── node_modules\
│   ├── nodemon\
│   ├── pm2\
│   └── ...

基本操作

安装全局模块

bash
# 安装全局模块
npm install -g <package-name>
npm install --global <package-name>

# 安装指定版本
npm install -g <package-name>@<version>
npm install -g eslint@8.0.0

# 安装最新版本
npm install -g <package-name>@latest

# 从 GitHub 安装
npm install -g github:user/repo

# 从 tarball 安装
npm install -g ./package.tgz

卸载全局模块

bash
# 卸载全局模块
npm uninstall -g <package-name>
npm un -g <package-name>

# 示例
npm uninstall -g nodemon

查看全局模块

bash
# 查看已安装的全局模块
npm list -g
npm ls -g

# 只显示顶层模块
npm list -g --depth=0

# 查看特定模块信息
npm list -g <package-name>
npm list -g nodemon

# 查看全局模块的详细信息
npm view <package-name>
npm info <package-name>

更新全局模块

bash
# 更新特定全局模块
npm update -g <package-name>

# 更新所有全局模块
npm update -g

# 检查过时的全局模块
npm outdated -g --depth=0

# 使用 npx 更新工具
npx npm-check-updates -g

推荐的全局模块

开发工具类

nodemon - 自动重启工具

自动监测文件变化并重启 Node.js 应用。

bash
npm install -g nodemon

基本使用

bash
# 直接运行
nodemon app.js

# 指定监听扩展名
nodemon --ext js,json,ts app.js

# 忽略特定目录
nodemon --ignore public/ --ignore logs/ app.js

# 延迟重启
nodemon --delay 2 app.js

# 传递参数给 Node.js
nodemon --inspect app.js

# 查看帮助
nodemon --help

配置文件 nodemon.json

json
{
  "watch": ["src"],
  "ext": "js,json,ts",
  "ignore": ["src/**/*.test.js", "logs/*"],
  "delay": 1000,
  "verbose": true,
  "env": {
    "NODE_ENV": "development",
    "PORT": 3000
  },
  "execMap": {
    "ts": "ts-node"
  }
}

package.json 配置

json
{
  "scripts": {
    "dev": "nodemon",
    "dev:debug": "nodemon --inspect"
  }
}

pm2 - 进程管理器

生产级 Node.js 进程管理器,支持集群、负载均衡、日志管理等。

bash
npm install -g pm2

基本命令

bash
# 启动应用
pm2 start app.js
pm2 start app.js --name my-api          # 指定名称
pm2 start app.js -i 4                   # 启动 4 个实例
pm2 start app.js --watch                # 监听文件变化

# 查看应用列表
pm2 list
pm2 status

# 查看应用详情
pm2 show my-api
pm2 describe my-api

# 日志管理
pm2 logs                                # 查看所有日志
pm2 logs my-api                         # 查看指定应用日志
pm2 logs --lines 100                    # 显示最后 100 行
pm2 flush                               # 清空所有日志
pm2 reloadLogs                          # 重新加载日志

# 应用控制
pm2 restart my-api                      # 重启应用
pm2 reload my-api                       # 零停机重启(集群模式)
pm2 stop my-api                         # 停止应用
pm2 delete my-api                       # 删除应用
pm2 stop all                            # 停止所有应用
pm2 delete all                          # 删除所有应用

# 监控
pm2 monit                               # 监控面板
pm2 plus                                # 连接到 PM2 Plus

配置文件 ecosystem.config.js

javascript
module.exports = {
  apps: [
    {
      name: 'my-api',
      script: './src/app.js',
      instances: 'max',           // 使用所有 CPU 核心
      exec_mode: 'cluster',       // 集群模式
      watch: false,               // 生产环境不监听文件
      max_memory_restart: '1G',   // 内存超过 1G 自动重启
      env: {
        NODE_ENV: 'development',
        PORT: 3000
      },
      env_production: {
        NODE_ENV: 'production',
        PORT: 80
      },
      error_file: './logs/error.log',
      out_file: './logs/out.log',
      log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
    },
    {
      name: 'worker',
      script: './src/worker.js',
      instances: 2,
      exec_mode: 'fork',
      watch: true,
      ignore_watch: ['node_modules', 'logs']
    }
  ]
};

使用配置文件

bash
# 启动所有应用
pm2 start ecosystem.config.js

# 使用生产环境变量
pm2 start ecosystem.config.js --env production

# 只启动特定应用
pm2 start ecosystem.config.js --only my-api

# 重启
pm2 restart ecosystem.config.js

# 停止
pm2 stop ecosystem.config.js

系统启动脚本

bash
# 生成启动脚本
pm2 startup

# 保存当前进程列表
pm2 save

# 恢复进程列表
pm2 resurrect

# 取消启动脚本
pm2 unstartup

http-server - 静态文件服务器

零配置的命令行 HTTP 服务器。

bash
npm install -g http-server

基本使用

bash
# 在当前目录启动
http-server

# 指定端口
http-server -p 8080

# 指定目录
http-server ./dist -p 8080

# 启用 CORS
http-server --cors

# 禁用缓存
http-server -c-1

# 启用缓存(设置过期时间)
http-server -c3600        # 缓存 1 小时

# 显示所有选项
http-server --help

常用选项

bash
# 完整示例
http-server ./public \
  -p 8080 \              # 端口
  -a localhost \         # 绑定地址
  --cors \               # 启用 CORS
  -c-1 \                 # 禁用缓存
  --gzip \               # 启用 gzip
  -o                     # 自动打开浏览器

live-server - 自动刷新服务器

带有实时刷新功能的开发服务器。

bash
npm install -g live-server

基本使用

bash
# 启动服务器
live-server

# 指定端口
live-server --port=8080

# 指定目录
live-server ./dist

# 不自动打开浏览器
live-server --no-browser

# 禁用浏览器通知
live-server --quiet

# 设置等待时间
live-server --wait=1000

配置文件 .liv-server.json

json
{
  "port": 8080,
  "root": "./public",
  "open": true,
  "wait": 1000,
  "ignore": "node_modules"
}

browser-sync - 多设备同步服务器

支持实时刷新和多设备同步的开发服务器。

bash
npm install -g browser-sync

静态网站模式

bash
# 启动服务器
browser-sync start --server --files "**/*"

# 监听特定文件
browser-sync start --server --files "css/*.css, js/*.js"

# 指定端口和目录
browser-sync start --server --files "**/*" --port 3000

# 不自动打开浏览器
browser-sync start --server --files "**/*" --no-open

代理模式

bash
# 代理到本地服务器
browser-sync start --proxy "localhost:8080" --files "**/*"

# 代理到指定域名
browser-sync start --proxy "myapp.dev" --files "css/*.css"

# 指定代理端口
browser-sync start --proxy "localhost:3000" --port 3001 --files "**/*"

配置文件 bs-config.js

javascript
module.exports = {
  files: ['**/*.html', '**/*.css', '**/*.js'],
  server: {
    baseDir: './',
    index: 'index.html'
  },
  port: 3000,
  open: true,
  notify: false,
  reloadOnRestart: true,
  ghostMode: {
    clicks: true,
    forms: true,
    scroll: true
  }
};

使用配置文件

bash
browser-sync start --config bs-config.js

工具对比

特性http-serverlive-serverbrowser-sync
自动刷新
多设备同步
代理模式
CSS 注入
配置复杂度简单简单中等
适用场景快速预览前端开发多设备测试

脚手架工具类

create-react-app - React 脚手架

React 官方脚手架工具。

bash
npm install -g create-react-app

# 或直接使用 npx(推荐)
npx create-react-app my-app

使用

bash
# 创建项目
create-react-app my-app

# 使用 TypeScript
create-react-app my-app --template typescript

# 使用特定模板
npx create-react-app my-app --template redux

# 启动开发服务器
cd my-app
npm start

# 构建生产版本
npm run build

# 运行测试
npm test

Vite - 下一代构建工具

极速的前端构建工具。

bash
npm install -g vite

# 或直接使用 npx(推荐)
npm create vite@latest

使用

bash
# 创建项目
npm create vite@latest my-project

# 选择模板
npm create vite@latest my-project -- --template react
npm create vite@latest my-project -- --template vue
npm create vite@latest my-project -- --template react-ts

# 启动开发服务器
vite

# 构建生产版本
vite build

# 预览生产构建
vite preview

@vue/cli - Vue 脚手架

Vue.js 官方脚手架工具。

bash
npm install -g @vue/cli

# 或使用 npx
npx @vue/cli create my-project

使用

bash
# 创建项目
vue create my-project

# 使用图形界面
vue ui

# 快速原型开发
vue serve App.vue
vue build App.vue

# 添加插件
vue add router
vue add vuex

代码质量工具类

ESLint - JavaScript 代码检查

可配置的 JavaScript 代码检查工具。

bash
npm install -g eslint

# 或在项目中使用(推荐)
npm install -D eslint

使用

bash
# 初始化配置
eslint --init

# 检查文件
eslint app.js

# 检查目录
eslint src/

# 自动修复
eslint --fix src/

# 使用配置文件
eslint -c .eslintrc.json src/

# 忽略特定文件
eslint --ignore-path .eslintignore src/

配置文件 .eslintrc.json

json
{
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  },
  "extends": ["eslint:recommended", "prettier"],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "rules": {
    "indent": ["error", 2],
    "quotes": ["error", "single"],
    "semi": ["error", "always"],
    "no-unused-vars": "warn",
    "no-console": "off"
  }
}

Prettier - 代码格式化

代码格式化工具,统一代码风格。

bash
npm install -g prettier

# 或在项目中使用(推荐)
npm install -D prettier

使用

bash
# 格式化文件
prettier --write app.js

# 格式化多个文件
prettier --write "src/**/*.{js,jsx,ts,tsx}"

# 检查格式(不修改)
prettier --check "src/**/*.js"

# 使用配置文件
prettier --config .prettierrc --write .

# 忽略文件
prettier --ignore-path .prettierignore --write .

配置文件 .prettierrc

json
{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 80,
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "endOfLine": "lf"
}

TypeScript - 类型检查

TypeScript 编译器。

bash
npm install -g typescript

# 或在项目中使用(推荐)
npm install -D typescript

使用

bash
# 编译文件
tsc app.ts

# 初始化配置
tsc --init

# 监听模式
tsc --watch

# 编译项目
tsc

# 指定配置文件
tsc --project tsconfig.build.json

# 版本检查
tsc --version

配置文件 tsconfig.json

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["ES2020", "DOM"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

实用工具类

rimraf - 跨平台删除

跨平台的 rm -rf 命令。

bash
npm install -g rimraf

# 或在项目中使用(推荐)
npm install -D rimraf

使用

bash
# 删除目录
rimraf node_modules
rimraf dist

# 删除文件
rimraf *.log

# 使用通配符
rimraf "dist/**/*.js"

# 在 package.json 中使用
npm pkg set scripts.clean="rimraf dist coverage"

# 运行
npm run clean

cross-env - 跨平台环境变量

跨平台设置环境变量的工具。

bash
npm install -g cross-env

# 或在项目中使用(推荐)
npm install -D cross-env

使用

bash
# 设置单个环境变量
cross-env NODE_ENV=production node app.js

# 设置多个环境变量
cross-env NODE_ENV=production PORT=3000 node app.js

# 在 package.json 中使用
npm pkg set scripts.build="cross-env NODE_ENV=production webpack"

# 运行
npm run build

concurrently - 并行执行命令

同时运行多个 npm 脚本。

bash
npm install -g concurrently

# 或在项目中使用(推荐)
npm install -D concurrently

使用

bash
# 并行运行命令
concurrently "npm run server" "npm run client"

# 命名进程
concurrently --names "SERVER,CLIENT" "npm run server" "npm run client"

# 使用不同颜色
concurrently --kill-others "npm run server" "npm run client"

# 在 package.json 中使用
npm pkg set scripts.dev="concurrently \"npm:server\" \"npm:client\""

json-server - Mock API 服务器

快速创建 REST API 模拟服务器。

bash
npm install -g json-server

使用

bash
# 创建 db.json
cat > db.json << EOF
{
  "posts": [
    { "id": 1, "title": "Post 1", "author": "Author 1" },
    { "id": 2, "title": "Post 2", "author": "Author 2" }
  ],
  "comments": [
    { "id": 1, "body": "Comment 1", "postId": 1 }
  ]
}
EOF

# 启动服务器
json-server --watch db.json

# 指定端口
json-server --watch db.json --port 3001

# 添加延迟
json-server --watch db.json --delay 1000

# 只读模式
json-server --watch db.json --read-only

API 端点

code
GET    /posts          # 获取所有文章
GET    /posts/1        # 获取单篇文章
POST   /posts          # 创建文章
PUT    /posts/1        # 更新文章
PATCH  /posts/1        # 部分更新
DELETE /posts/1        # 删除文章

GET    /posts?title=Post 1     # 过滤
GET    /posts?_sort=id&_order=desc  # 排序
GET    /posts?_page=1&_limit=10     # 分页
GET    /posts/1?_embed=comments     # 关联查询

nrm - 镜像源管理

npm 镜像源管理工具。

bash
npm install -g nrm

使用

bash
# 列出所有镜像源
nrm ls

# 切换镜像源
nrm use taobao

# 测试速度
nrm test

# 添加自定义源
nrm add company http://npm.company.com

# 删除镜像源
nrm del company

# 查看当前源
nrm current

环境配置

修改全局安装路径

方案一:修改 npm prefix(推荐)

macOS/Linux

bash
# 创建全局目录
mkdir ~/.npm-global

# 设置全局路径
npm config set prefix '~/.npm-global'

# 添加到 PATH
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
# 或
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc

# 重新加载配置
source ~/.bashrc  # 或 source ~/.zshrc

# 验证
npm config get prefix

Windows

powershell
# 创建全局目录
mkdir $env:USERPROFILE\npm-global

# 设置全局路径
npm config set prefix "$env:USERPROFILE\npm-global"

# 添加到环境变量
setx PATH "%PATH%;%USERPROFILE%\npm-global"

# 重启终端后验证
npm config get prefix

方案二:使用 nvm(推荐)

使用 nvm 管理 Node.js 版本,全局模块会自动安装在 nvm 管理的目录下,避免权限问题。

bash
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# 安装 Node.js
nvm install node

# 全局模块自动安装到
# ~/.nvm/versions/node/v20.x.x/lib/node_modules

环境变量说明

NODE_PATH

指定 Node.js 模块搜索路径:

bash
# macOS/Linux
export NODE_PATH=$(npm root -g)

# 添加到配置文件
echo "export NODE_PATH=\$(npm root -g)" >> ~/.bashrc

注意:不推荐设置 NODE_PATH,可能导致模块解析混乱。

PATH

确保全局命令可用:

bash
# macOS/Linux
export PATH=$(npm bin -g):$PATH

# 或使用绝对路径
export PATH=/usr/local/bin:$PATH
powershell
# Windows
setx PATH "%PATH%;C:\Users\<username>\AppData\Roaming\npm"

常见问题与故障排除

1. 权限问题(EACCES)

错误信息

code
npm ERR! Error: EACCES: permission denied
npm ERR!  /usr/local/lib/node_modules

解决方案

方案一:修改 npm 全局路径(推荐)

bash
# 创建用户级全局目录
mkdir ~/.npm-global

# 设置 npm 使用新路径
npm config set prefix '~/.npm-global'

# 添加到 PATH
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

方案二:修改目录权限(不推荐)

bash
# 修改 npm 目录所有者
sudo chown -R $(whoami) /usr/local/lib/node_modules
sudo chown -R $(whoami) /usr/local/bin
sudo chown -R $(whoami) /usr/local/share

方案三:使用 nvm(推荐)

bash
# 安装 nvm,避免权限问题
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install node

2. 命令找不到

错误信息

code
bash: nodemon: command not found

解决方案

bash
# 1. 检查全局模块是否安装
npm list -g nodemon

# 2. 检查 PATH 是否包含 npm bin
echo $PATH

# 3. 查看 npm bin 路径
npm bin -g

# 4. 添加到 PATH
export PATH=$(npm bin -g):$PATH

# 5. 重新安装
npm install -g nodemon

3. 版本冲突

问题:全局安装的工具版本与项目需求不一致。

解决方案

bash
# 方案一:使用 npx(推荐)
npx eslint@8.0.0 src/

# 方案二:本地安装(推荐)
npm install -D eslint@8.0.0

# 方案三:更新全局版本
npm update -g eslint

4. Windows 路径问题

问题:Windows 下路径分隔符导致脚本执行失败。

解决方案

json
// package.json
{
  "scripts": {
    "clean": "rimraf dist/**/*",
    "build": "cross-env NODE_ENV=production webpack"
  },
  "devDependencies": {
    "rimraf": "^5.0.0",
    "cross-env": "^7.0.0"
  }
}

5. 全局模块更新失败

问题:更新全局模块时报错。

解决方案

bash
# 1. 清理缓存
npm cache clean --force

# 2. 卸载后重新安装
npm uninstall -g <package-name>
npm install -g <package-name>

# 3. 使用 npx 临时使用最新版
npx <package-name>@latest

6. 符号链接问题(Windows)

问题:Windows 开发者模式下符号链接权限问题。

解决方案

powershell
# 1. 以管理员身份运行 PowerShell

# 2. 启用开发者模式
# 设置 -> 更新和安全 -> 开发者选项 -> 开发者模式

# 3. 或使用 npm 3+,自动处理符号链接
npm install -g <package-name>

最佳实践

1. 优先使用 npx

推荐做法

bash
# ❌ 不推荐:全局安装脚手架
npm install -g create-react-app
create-react-app my-app

# ✅ 推荐:使用 npx
npx create-react-app my-app

# ✅ 推荐:使用 npx 指定版本
npx create-react-app@5.0.0 my-app

优点

  • 不污染全局环境
  • 总是使用最新版本
  • 避免版本冲突
  • 减少磁盘占用

2. 区分全局和本地安装

全局安装(CLI 工具):

bash
# ✅ 全局安装
npm install -g pm2           # 进程管理
npm install -g nodemon       # 开发工具
npm install -g nrm           # 镜像源管理

本地安装(项目依赖):

bash
# ✅ 本地安装
npm install -D eslint        # 代码检查
npm install -D prettier      # 代码格式化
npm install -D webpack       # 构建工具
npm install -D jest          # 测试框架

3. 项目配置优于全局配置

推荐做法

json
// package.json
{
  "devDependencies": {
    "eslint": "^8.0.0",
    "prettier": "^3.0.0",
    "nodemon": "^3.0.0"
  },
  "scripts": {
    "lint": "eslint src/",
    "format": "prettier --write .",
    "dev": "nodemon src/index.js"
  }
}

优点

  • 团队版本一致
  • 配置可追溯
  • 易于维护

4. 定期清理全局模块

bash
# 查看全局模块
npm list -g --depth=0

# 卸载不常用的模块
npm uninstall -g <package-name>

# 或重新安装 Node.js 后重新安装需要的全局模块

5. 使用 package.json 管理全局工具

创建专门的全局工具项目:

bash
# 创建全局工具项目
mkdir ~/global-tools
cd ~/global-tools
npm init -y

# 安装常用工具
npm install --save-dev nodemon pm2 eslint prettier

# 创建脚本
npm pkg set scripts.dev="nodemon"
npm pkg set scripts.lint="eslint"

6. 文档化全局依赖

创建全局依赖清单

markdown
# 全局模块清单

## 开发工具
- nodemon: ^3.0.0 - 自动重启工具
- pm2: ^5.0.0 - 进程管理器
- http-server: ^14.0.0 - 静态服务器

## 代码质量
- eslint: ^8.0.0 - 代码检查
- prettier: ^3.0.0 - 代码格式化

## 实用工具
- nrm: ^1.0.0 - 镜像源管理
- rimraf: ^5.0.0 - 删除工具

7. 版本锁定策略

对于关键全局工具,锁定版本:

bash
# 安装特定版本
npm install -g eslint@8.50.0

# 查看已安装版本
npm list -g eslint

# 更新到特定版本
npm install -g eslint@8.51.0

8. 避免全局模块依赖

问题:项目依赖全局模块会导致其他开发者无法运行。

解决方案

json
// ❌ 不推荐:依赖全局模块
{
  "scripts": {
    "dev": "nodemon app.js"  // 需要全局安装 nodemon
  }
}

// ✅ 推荐:本地安装
{
  "devDependencies": {
    "nodemon": "^3.0.0"
  },
  "scripts": {
    "dev": "nodemon app.js"
  }
}

9. 使用 Docker 管理环境

对于团队项目,使用 Docker 统一环境:

dockerfile
# Dockerfile
FROM node:20-alpine

# 安装全局工具
RUN npm install -g pm2 nodemon

# 安装项目依赖
COPY package*.json ./
RUN npm install

COPY . .

CMD ["pm2-runtime", "app.js"]

10. CI/CD 环境配置

yaml
# .github/workflows/ci.yml
- name: Setup Node.js
  uses: actions/setup-node@v3
  with:
    node-version: '20'

- name: Install global tools
  run: |
    npm install -g pm2
    npm install -g eslint

- name: Install dependencies
  run: npm ci

参考资料


Node.js 22+ 全局模块新趋势

Node.js 内置工具替代全局模块

Node.js 22+ 内置了多个以前需要全局安装的工具功能,减少了对第三方全局模块的依赖:

全局模块Node.js 内置替代版本说明
nodemonnode --watchv22 稳定文件监视自动重启
dotenvnode --env-filev20.6+环境变量文件加载
ts-node / tsx--experimental-strip-typesv22.6+直接运行 TypeScript
npm runnode --runv23 稳定运行 package.json 脚本
node-fetch全局 fetchv22 稳定HTTP 请求
ws全局 WebSocketv23 稳定WebSocket 客户端
jest / mochanode:testv22 稳定内置测试框架

npx 替代方案

bash
# 传统 npx
npx create-react-app my-app

# Node.js 22+ 推荐使用 Corepack
corepack enable
corepack prepare pnpm@latest --activate

# 或使用 --run 替代部分 npx 场景
node --run create