简介:本文详细解析Node.js、npm与yarn的安装流程,涵盖版本选择、环境配置、验证测试及常见问题解决,助力开发者快速搭建高效开发环境。
在JavaScript生态中,Node.js作为服务端运行环境,npm作为包管理工具,yarn作为优化后的依赖管理方案,三者共同构成现代前端开发的基石。安装前需明确:
Windows/macOS:
node -v和npm -v,应返回版本号。Linux(Ubuntu/Debian):
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -sudo apt-get install -y nodejs
nvm(Node Version Manager):
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash
nvm install 18.16.0 # 安装指定版本nvm use 18.16.0 # 切换版本nvm alias default 18.16.0 # 设置默认版本
n(轻量级替代方案):
npm install -g nn lts # 安装最新LTS版
npm config set registry https://registry.npmmirror.com
npm init -y # 快速生成package.jsonnpm install lodash # 安装依赖npm list # 查看依赖树
npm install -g yarn
curl -o- -L https://yarnpkg.com/install.sh | bash
yarn install)。yarn.lock锁定版本。在package.json中添加脚本:
{"scripts": {"start": "node server.js","dev": "nodemon server.js","build": "webpack"}}
执行脚本:
yarn dev # 或 npm run dev
echo $PATH | grep node # macOS/Linuxwhere node # Windows
npm install -g create-react-appcreate-react-app test-app
sudo chown -R $(whoami) /usr/local/lib/node_modules
nvm uninstall 16.14.0 # 卸载旧版本nvm install 18.16.0 # 重新安装
npm config set proxy http://proxy.company.com:8080
npx degit user/repo my-project # 从Git仓库初始化
yarn config set cache-folder ~/.yarn/cache
npm config set cache ~/.npm
npm outdatednpm update
npm audit检查漏洞。
FROM node:18-alpineWORKDIR /appCOPY package.json yarn.lock ./RUN yarn install --frozen-lockfileCOPY . .CMD ["yarn", "start"]
通过系统化的环境搭建,开发者可显著提升开发效率,减少因环境问题导致的调试时间。建议每季度检查一次版本更新,保持技术栈的现代性。