前端工程化

前端工程化的概念、工具链和实践

问题

什么是前端工程化?包含哪些内容?如何搭建一个工程化项目?

解答

前端工程化是将软件工程的方法应用到前端开发中,通过工具和规范提升开发效率、保证代码质量。

工程化的主要组成

前端工程化
├── 模块化        # ES Modules / CommonJS
├── 包管理        # npm / yarn / pnpm
├── 构建工具      # Vite / Webpack / Rollup
├── 代码规范      # ESLint / Prettier
├── 类型检查      # TypeScript
├── 测试          # Jest / Vitest
├── 版本控制      # Git
└── CI/CD        # GitHub Actions / Jenkins

1. 模块化

// ES Modules (推荐)
// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

// main.js
import { add, multiply } from './math.js';

// CommonJS (Node.js)
// utils.js
module.exports = {
  formatDate: (date) => date.toISOString()
};

// app.js
const { formatDate } = require('./utils.js');

2. 包管理 - package.json

{
  "name": "my-project",
  "version": "1.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint src --fix",
    "test": "vitest"
  },
  "dependencies": {
    "vue": "^3.4.0"
  },
  "devDependencies": {
    "vite": "^5.0.0",
    "eslint": "^8.56.0",
    "typescript": "^5.3.0"
  }
}

3. 构建工具 - Vite 配置

// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
  plugins: [vue()],
  
  // 路径别名
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  
  // 开发服务器
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      }
    }
  },
  
  // 构建配置
  build: {
    outDir: 'dist',
    rollupOptions: {
      output: {
        // 分包策略
        manualChunks: {
          vendor: ['vue', 'vue-router']
        }
      }
    }
  }
});

4. 代码规范 - ESLint + Prettier

// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'prettier' // 放最后,覆盖其他规则
  ],
  rules: {
    'no-console': 'warn',
    'no-unused-vars': 'error',
    'vue/multi-word-component-names': 'off'
  }
};
// .prettierrc
{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 80
}

5. TypeScript 配置

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "types": ["vite/client"]
  },
  "include": ["src/**/*.ts", "src/**/*.vue"],
  "exclude": ["node_modules"]
}

6. Git 规范 - Husky + Commitlint

# 安装
npm install husky lint-staged @commitlint/cli @commitlint/config-conventional -D

# 初始化 husky
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"
npx husky add .husky/commit-msg "npx commitlint --edit $1"
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  // feat: 新功能
  // fix: 修复
  // docs: 文档
  // style: 格式
  // refactor: 重构
  // test: 测试
  // chore: 构建/工具
};
// package.json 中添加
{
  "lint-staged": {
    "*.{js,ts,vue}": ["eslint --fix", "prettier --write"],
    "*.{css,scss}": ["prettier --write"]
  }
}

7. CI/CD - GitHub Actions

# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Lint
        run: npm run lint
      
      - name: Test
        run: npm run test
      
      - name: Build
        run: npm run build

完整项目结构

my-project/
├── .github/
│   └── workflows/
│       └── ci.yml
├── .husky/
│   ├── pre-commit
│   └── commit-msg
├── src/
│   ├── assets/
│   ├── components/
│   ├── views/
│   ├── utils/
│   ├── App.vue
│   └── main.ts
├── public/
├── .eslintrc.js
├── .prettierrc
├── .gitignore
├── commitlint.config.js
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.js

关键点

  • 模块化:ES Modules 是标准,支持 Tree Shaking
  • 构建工具:Vite 开发快(ESBuild),Webpack 生态成熟
  • 代码规范:ESLint 检查语法,Prettier 统一格式,两者配合使用
  • Git 规范:Husky 拦截提交,lint-staged 只检查暂存文件
  • TypeScript:类型检查在编译时发现错误,提升代码可维护性
  • CI/CD:自动化测试和部署,保证代码质量