温馨提示×

Ubuntu如何使用Node.js进行前端构建

小樊
39
2025-11-26 23:44:42
栏目: 编程语言

在 Ubuntu 上使用 Node.js 进行前端构建

一 环境准备

  • 安装 Node.js 与 npm(两种常用方式,择一即可)
    • 使用 NodeSource 安装 LTS 版本(推荐):
      curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
      sudo apt-get install -y nodejs
      
    • 使用 nvm(便于多版本管理):
      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
      # 重新加载 shell 后
      nvm install --lts
      nvm use --lts
      
  • 验证安装:
    node -v
    npm -v
    
  • 可选:切换为国内镜像源以加速依赖安装
    npm config set registry https://registry.npm.taobao.org
    # 查看
    npm config get registry
    # 还原
    npm config set registry https://registry.npmjs.org/
    

以上步骤完成后,即可在 Ubuntu 上具备前端构建所需的 Node.js/npm 环境。

二 初始化项目与安装依赖

  • 创建并进入项目目录:
    mkdir my-frontend && cd $_
    npm init -y
    
  • 安装常用构建相关依赖(示例):
    npm i -D webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env sass sass-loader css-loader style-loader html-webpack-plugin
    
  • 目录约定示例:
    my-frontend/
    ├─ src/
    │  ├─ index.js
    │  └─ style.scss
    ├─ public/
    │  └─ index.html
    ├─ webpack.config.js
    └─ package.json
    

上述依赖覆盖 打包(Webpack)转译(Babel)样式预处理(Sass)开发服务器(webpack-dev-server) 等常见前端构建能力。

三 配置与常用命令

  • 示例 webpack.config.js(开发与生产共用的基础配置)
    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = (env, argv) => {
      const isProd = argv.mode === 'production';
      return {
        entry: './src/index.js',
        output: {
          path: path.resolve(__dirname, 'dist'),
          filename: isProd ? '[name].[contenthash].js' : '[name].js',
          clean: true,
        },
        module: {
          rules: [
            {
              test: /\.js$/,
              exclude: /node_modules/,
              use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } },
            },
            {
              test: /\.s[ac]ss$/,
              use: ['style-loader', 'css-loader', 'sass-loader'],
            },
          ],
        },
        plugins: [new HtmlWebpackPlugin({ template: './public/index.html' })],
        devServer: isProd
          ? undefined
          : {
              static: { directory: path.join(__dirname, 'public') },
              port: 3000,
              hot: true,
              open: true,
            },
      };
    };
    
  • package.json 中添加脚本:
    {
      "scripts": {
        "dev": "webpack serve --mode development",
        "build": "webpack --mode production"
      }
    }
    
  • 常用命令:
    # 开发:启动本地服务(默认端口 3000)
    npm run dev
    
    # 生产:生成优化后的静态文件到 dist/
    npm run build
    

该配置示例展示了使用 Webpack 进行模块打包、使用 Babel 转译 ES6+、使用 Sass 处理样式,并通过 HtmlWebpackPlugin 生成 HTML 入口;开发阶段启用 webpack-dev-server 的热更新能力。

四 生产部署与自动化

  • 使用 Nginx 托管静态资源
    • 将构建产物 dist/ 部署到 /var/www/myapp,配置 Nginx:
      sudo apt-get install -y nginx
      sudo rm -f /etc/nginx/sites-enabled/default
      sudo tee /etc/nginx/sites-available/myapp <<'EOF'
      server {
        listen 80;
        server_name your-domain.com;
        root /var/www/myapp;
        index index.html;
        location / {
          try_files $uri $uri/ /index.html;
        }
      }
      EOF
      sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
      sudo nginx -t && sudo systemctl reload nginx
      
  • 使用 Jenkins 实现自动化构建与发布
    • 在 Jenkins 中安装 NodeJS 插件,在“全局工具配置”里添加 Node.js 安装;
    • 新建任务 → 源码管理选择 Git → 构建环境勾选 Provide Node & npm bin/ folder to PATH
    • 构建步骤执行:
      npm ci
      npm run build
      tar -zcf dist.tar.gz -C dist .
      
    • 构建后操作使用 Publish Over SSHdist.tar.gz 传到目标服务器并解压到 /var/www/myapp,完成发布。 以上流程覆盖在 Ubuntu 上以 Nginx 托管前端静态资源,以及用 Jenkins 完成拉取代码、安装依赖、构建与发布的自动化实践。

0