温馨提示×

Debian如何配置JS开发环境

小樊
35
2025-12-03 07:36:03
栏目: 编程语言

在 Debian 上搭建 JavaScript 开发环境

一 安装 Node.js 与 npm

  • 更新索引并安装基础工具
    • sudo apt update && sudo apt install -y curl ca-certificates gnupg lsb-release
  • 方式一 使用 NodeSource 仓库安装(推荐,版本可控)
    • 安装 LTS(示例):curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
    • 或安装指定主版本(示例):curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    • 安装:sudo apt install -y nodejs
    • 验证:node -v 与 npm -v 显示版本号
  • 方式二 使用 NVM 多版本管理(适合切换多个 Node 版本)
    • 安装:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    • 重载环境:source ~/.bashrc(或 source ~/.zshrc)
    • 安装与默认:nvm install --lts;nvm alias default lts/*;nvm use --lts
    • 验证:node -v 与 npm -v

二 配置 npm 与全局包路径

  • 配置国内镜像加速(可选,提升下载速度)
    • npm config set registry https://registry.npmmirror.com
    • 验证:npm config get registry
  • 自定义全局包目录(避免写入系统目录,便于权限管理)
    • 创建目录:mkdir -p ~/.npm-global
    • 设置前缀:npm config set prefix ‘~/.npm-global’
    • 将可执行目录加入 PATH(写入 ~/.bashrc 或 ~/.zshrc):export PATH=~/.npm-global/bin:$PATH
    • 使配置生效:source ~/.bashrc(或 source ~/.zshrc)
    • 验证:npm root -g 应指向 ~/.npm-global/lib/node_modules

三 开发工具与常用全局包

  • 编辑器与调试
    • 安装 VS Code:sudo apt update && sudo apt install -y wget gpg;wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /usr/share/keyrings/packages.microsoft.gpg > /dev/null;echo “deb [arch=amd64 signed-by=/usr/share/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main” | sudo tee /etc/apt/sources.list.d/vscode.list > /dev/null;sudo apt update && sudo apt install -y code
    • 推荐扩展:ESLintPrettierJavaScript Debugger
  • 常用全局工具
    • npm install -g yarn pm2 nodemon typescript eslint
    • 验证:yarn -v、pm2 -v、nodemon -v、tsc -v、eslint -v

四 创建项目与运行示例

  • 初始化与依赖
    • mkdir myapp && cd myapp
    • npm init -y
    • npm install express
  • 最小 HTTP 服务示例 app.js
    • const express = require(‘express’); const app = express(); const port = process.env.PORT || 3000; app.get(‘/’, (_, res) => res.send(‘Hello from Debian Node.js’)); app.listen(port, () => console.log(Server listening on ${port}));
  • 启动与热重载
    • 开发:nodemon app.js
    • 生产:pm2 start app.js --name “myapp”;pm2 startup;pm2 save

五 部署与反向代理(可选)

  • 使用 Nginx 反向代理到 Node 服务
    • 安装:sudo apt install -y nginx
    • 配置 /etc/nginx/sites-available/default(示例)
      • server { listen 80; server_name your_domain_or_ip; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection ‘upgrade’; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
    • 校验与生效:sudo nginx -t && sudo systemctl reload nginx
  • 云服务器安全组/防火墙需放行 80/443 端口,或按需使用自定义端口并同步调整 Nginx 与防火墙策略

0