前端工程化 · 26/90
1. Babel 的工作原理 2. body-parser 中间件的作用 3. Babel 转译原理 4. 浏览器和 Node 中的事件循环区别 5. 职责链模式 6. 链模式 7. 命令模式 8. 组件封装设计 9. 数据统计 10. dependencies 和 devDependencies 的区别 11. CommonJS 和 ES6 模块引入的区别 12. 设计模式分类 13. 前端开发中常用的设计模式 14. 设计模式应用场景 15. 设计原则 16. 开发环境搭建要点 17. Electron 理解 18. 前后端分离是什么 19. 工厂模式 20. 前端代码重构 21. 前端组件化 22. 前端工程师职业发展 23. 前端工程化方向 24. 前端工程化的理解 25. 前端工程价值体现 26. 前端工程化 27. Git 常用命令与工作流 28. Gulp 任务自动化工具 29. 图片导出 30. 前端模块化规范 31. 迭代器模式 32. JavaScript 编码规范 33. 前端 CI/CD 流程 34. jQuery 生态对比 35. jQuery 实现原理 36. jQuery 与 Sizzle 选择器集成 37. Koa 中间件异常处理 38. jQuery 源码优秀实践 39. jQuery 与 Zepto 对比 40. jQuery UI 自定义组件 41. Koa 中间件不调用 await next() 的影响 42. Koa 在没有 async/await 时如何实现洋葱模型 43. Koa 和 Express 的区别 44. Koa 洋葱模型 45. 登录实现 46. 中介者模式 47. 模块模式 48. 小程序架构 49. 小程序常见问题 50. Monorepo 概念与工具 51. mpvue 框架 52. MVC vs MVP vs MVVM 53. Node.js ES Module 为什么必须加文件扩展名 54. MVC、MVP 和 MVVM 架构模式 55. Node.js 全局对象 56. Node.js 性能监控与优化 57. Node.js 多进程与进程通讯 58. Node.js 调试方法 59. Node.js 中的 process 对象 60. Node.js 的理解与应用场景 61. npm 是什么? 62. 观察者模式和发布订阅模式的区别 63. 页面重构方法 64. PM2 守护进程原理 65. 分页功能的前后端设计 66. PostCSS 作用 67. 项目管理方法 68. Rollup 打包工具 69. 高质量前端代码 70. JavaScript 单例模式实现 71. SSG 静态网站生成 72. 模板方法模式 73. 设计模式的六大原则 74. Tree Shaking 原理 75. 用户授权信息获取流程 76. Vite 原理与性能优势 77. Web App vs Hybrid App vs Native App 78. Web 前端开发注意事项 79. Web APP 设计原则 80. Webpack 构建流程 81. Hash vs ChunkHash vs ContentHash 82. Webpack 热更新原理 83. Webpack Loader 与 Plugin 区别 84. webpack 的 module、bundle、chunk 是什么 85. Webpack Proxy 工作原理与跨域解决 86. webpack、rollup、parcel 的选择 87. WePy 与 mpvue 对比 88. WXML 和 WXSS 89. Webpack Scope Hoisting 90. Zepto 实现原理

前端工程化

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

问题

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

解答

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

工程化的主要组成

前端工程化
├── 模块化        # 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:自动化测试和部署,保证代码质量