Node.js 已成为现代 Web 开发不可或缺的运行时环境。无论是前端工程化(Webpack、Vite)、后端服务(Express、Koa),还是桌面应用(Electron),都离不开 Node.js。本文从零开始,详细介绍 Node.js 开发环境的搭建步骤和最佳实践。
一、Node.js 版本管理
为什么需要版本管理?
Node.js 版本迭代很快,不同项目可能依赖不同的 Node.js 版本:
1 2 3
| 项目 A → Node.js 16.x(旧项目兼容) 项目 B → Node.js 18.x(LTS 稳定) 项目 C → Node.js 20.x(最新特性)
|
手动切换版本非常麻烦,因此推荐使用版本管理工具。
nvm(Node Version Manager)
nvm 是目前最流行的 Node.js 版本管理工具,支持在多个版本间自由切换。
Linux / macOS 安装
1 2 3 4 5
| curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
|
安装完成后,重新打开终端或执行以下命令使配置生效:
验证安装:
Windows 安装(nvm-windows)
Windows 下需要使用专门的 nvm-windows:
- 访问 nvm-windows 发布页
- 下载
nvm-setup.exe
- 以管理员身份运行安装程序
- 按照向导完成安装
安装后打开 PowerShell 验证:
nvm 常用命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| nvm ls-remote
nvm ls
nvm install 20.11.0 nvm install 18.19.0
nvm install --lts
nvm use 20.11.0
nvm alias default 20.11.0
nvm uninstall 16.20.0
|
二、安装 Node.js
如果不需要多版本管理,也可以直接安装官方包。
方式一:使用 nvm(推荐)
1 2 3 4 5 6 7 8
| nvm install --lts
nvm install node
nvm alias default $(nvm current)
|
方式二:官方安装包
访问 Node.js 官网 下载对应系统的安装包:
- LTS 版本:长期支持版,适合大多数项目
- Current 版本:最新特性版,适合开发测试
Windows 安装
下载 .msi 安装包,双击运行,一路 Next 即可。安装过程中建议勾选”Add to PATH”选项。
Linux(Ubuntu/Debian)通过包管理器安装
1 2 3 4 5 6 7
| curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - sudo apt-get install -y nodejs
node --version npm --version
|
验证安装
1 2
| node --version npm --version
|
创建一个简单的测试文件:
1 2 3 4 5 6 7 8 9 10 11
| const http = require('http');
const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, Node.js!\n'); });
server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
|
运行:
访问 http://localhost:3000/ 看到 Hello, Node.js! 即表示安装成功。
三、包管理工具
npm(Node Package Manager)
npm 是 Node.js 自带的包管理器,无需额外安装。
配置 npm 镜像源
国内用户建议配置淘宝镜像,提高下载速度:
1 2 3 4 5 6 7 8
| npm config get registry
npm config set registry https://registry.npmmirror.com
npm config set registry https://registry.npmjs.org
|
常用命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| npm init -y
npm install express npm install -D typescript npm install -g nodemon
npm update express
npm uninstall express
npm list --depth=0
npm outdated
npm audit fix
|
yarn
Facebook 推出的包管理工具,以速度和可靠性著称。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| npm install -g yarn
yarn --version
yarn init -y
yarn add express yarn add -D typescript
yarn install
yarn remove express
|
pnpm
新一代包管理工具,使用硬链接节省磁盘空间。
1 2 3 4 5 6 7
| npm install -g pnpm
pnpm init pnpm add express pnpm install
|
各工具对比
| 特性 | npm | yarn | pnpm |
| 速度 | 一般 | 较快 | 最快 |
| 磁盘占用 | 较高 | 较高 | 最低(硬链接) |
| 内置支持 | Node.js 自带 | 需额外安装 | 需额外安装 |
| lock 文件 | package-lock.json | yarn.lock | pnpm-lock.yaml |
| 严格模式 | 否 | 否 | 是(幽灵依赖隔离) |
四、VS Code 配置
VS Code 是 Node.js 开发的理想编辑器。
推荐扩展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| # 基础必装 - ESLint(代码检查) - Prettier(代码格式化) - npm Intellisense(npm 导入自动补全) - Path Intellisense(路径补全)
# 调试辅助 - JavaScript Debugger(内置,无需单独安装) - REST Client(接口调试)
# 增强体验 - GitLens(Git 历史可视化) - Bracket Pair Colorizer 2(括号着色) - Import Cost(显示导入包大小) - npm Dependency(依赖关系可视化)
|
settings.json 推荐配置
1 2 3 4 5 6 7 8 9 10 11 12 13
| { "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, "npm.enableScriptExplorer": true, "files.exclude": { "**/node_modules": true }, "javascript.updateImportsOnFileMove.enabled": "always", "typescript.updateImportsOnFileMove.enabled": "always" }
|
Launch.json 调试配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "启动程序", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/index.js" }, { "type": "node", "request": "attach", "name": "附加到进程", "port": 9229 }, { "type": "node", "request": "launch", "name": "通过 NPM 启动", "runtimeExecutable": "npm", "runtimeArgs": ["run", "dev"], "console": "integratedTerminal" } ] }
|
五、常用开发工具链
ESLint + Prettier 配置
1 2 3 4 5
| npm install -D eslint prettier eslint-config-prettier eslint-plugin-prettier
npx eslint --init
|
.eslintrc.json 参考配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| { "env": { "node": true, "es2021": true }, "extends": [ "eslint:recommended", "plugin:prettier/recommended" ], "parserOptions": { "ecmaVersion": "latest", "sourceType": "module" }, "rules": { "no-console": "warn", "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], "prettier/prettier": "error" } }
|
.prettierrc 参考配置:
1 2 3 4 5 6 7 8 9
| { "semi": true, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5", "printWidth": 100, "arrowParens": "always", "endOfLine": "lf" }
|
nodemon(自动重启)
开发过程中,每次修改代码都需要手动重启服务,非常低效。nodemon 可以监听文件变化自动重启:
1 2 3 4 5 6 7
| npm install -g nodemon
nodemon index.js
|
1 2 3 4 5 6
| { "scripts": { "dev": "nodemon index.js", "start": "node index.js" } }
|
环境变量管理
推荐使用 dotenv 管理环境变量:
1 2 3 4 5 6 7 8 9 10 11 12
| PORT=3000 DB_HOST=localhost DB_USER=root DB_PASSWORD=your_password JWT_SECRET=your_secret_key
require('dotenv').config();
const port = process.env.PORT || 3000; console.log(`Server running on port ${port}`);
|
常用调试技术
Node.js 内置了强大的调试能力:
1 2 3 4 5
| node --inspect index.js
node --inspect-brk index.js
|
然后在 Chrome 浏览器中打开 chrome://inspect,点击 “Open dedicated DevTools for Node” 即可开始调试。
六、npm scripts 最佳实践
合理组织 package.json 中的 scripts 字段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| { "scripts": { "dev": "nodemon index.js", "start": "node index.js", "build": "node build.js", "lint": "eslint src/", "lint:fix": "eslint src/ --fix", "format": "prettier --write src/", "test": "jest", "test:watch": "jest --watch", "precommit": "npm run lint && npm run test", "prepare": "husky install" } }
|
七、常见问题排查
问题 1:npm install 速度极慢
1 2 3
| 原因:默认 registry 在国外 解决: npm config set registry https://registry.npmmirror.com
|
问题 2:node: command not found
1 2 3 4 5
| 原因:Node.js 未添加到 PATH 解决: Windows: 重新安装并勾选 "Add to PATH" Linux: export PATH=$PATH:/usr/local/bin/node nvm: nvm use default
|
问题 3:npm 权限错误(Linux/macOS)
1 2 3 4 5 6 7 8
| 错误:EACCES: permission denied 原因:全局安装时缺少权限 解决: 方案一:使用 nvm 管理(推荐) 方案二:配置 npm 全局目录 mkdir ~/.npm-global npm config set prefix '~/.npm-global' export PATH=~/.npm-global/bin:$PATH
|
问题 4:端口被占用
1 2 3 4 5 6 7 8 9 10 11 12 13
|
lsof -i :3000
netstat -ano | findstr :3000
kill -9 <PID>
taskkill /PID <PID> /F
|
八、快速脚本:一键搭建开发环境
以下是一个自动化脚本,一键配置 Node.js 开发环境(Linux/macOS):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #!/bin/bash
set -e
echo "===== Node.js 开发环境搭建 ====="
if [ ! -d "$HOME/.nvm" ]; then echo "[1/4] 安装 nvm..." curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash source ~/.bashrc else echo "[1/4] nvm 已安装,跳过" fi
echo "[2/4] 安装 Node.js LTS..." nvm install --lts nvm alias default $(nvm current)
echo "[3/4] 配置 npm 镜像..." npm config set registry https://registry.npmmirror.com
echo "[4/4] 安装全局工具..." npm install -g nodemon eslint prettier
echo "" echo "===== 搭建完成 =====" echo "Node.js: $(node --version)" echo "npm: $(npm --version)" echo "nvm: $(nvm --version 2>/dev/null || echo '需重启终端')" echo "" echo "本地服务器测试:node -e \"require('http').createServer((_,r)=>{r.end('OK')}).listen(3000,()=>console.log('http://localhost:3000'))\""
|
九、总结
Node.js 开发环境搭建看似简单,但做好版本管理、包管理、代码规范和调试配置,可以显著提升开发效率。
环境搭建核心要点:
- 使用 nvm 管理版本 — 灵活切换,避免冲突
- 配置国内镜像源 — 大幅提升安装速度
- 统一代码风格 — ESLint + Prettier 保持团队一致
- 合理使用 npm scripts — 将常用命令脚本化
- 配置调试环境 — 善用 VS Code + Node.js inspector
掌握了这些基础,就可以开始 Node.js 项目的开发了。无论是构建博客系统、RESTful API,还是学习 TypeScript、Next.js 等现代框架,一个稳定的开发环境都是高效工作的基石。
本文由AI辅助生成,内容仅供参考