ai-coding-demo

什么是前端构建?

📖 概述

前端构建是现代 Web 开发中的重要流程,指将源代码转换为生产可用的优化代码的过程。它包括代码转换、模块打包、资源优化、代码压缩等多个步骤,极大提升了开发效率和代码质量。

🌟 构建的作用

1. 代码转换

2. 模块打包

3. 性能优化

4. 开发辅助

🛠️ 常见构建工具

1. Webpack

// webpack.config.js
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      { test: /\.js$/, use: 'babel-loader' },
      { test: /\.css$/, use: ['style-loader', 'css-loader'] }
    ]
  }
}

2. Vite

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

export default defineConfig({
  plugins: [vue()],
  build: {
    outDir: 'dist',
    sourcemap: true
  }
})

3. Parcel

// package.json
{
  "scripts": {
    "build": "parcel build src/index.html"
  }
}

4. Rollup

// rollup.config.js
export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'esm'
  }
}

📦 构建流程

1. 开发阶段

# 启动开发服务器
npm run dev
# - 开启 HMR
# - 实时编译
# - Source Map
# - 错误提示

2. 构建阶段

# 生产构建
npm run build
# - 代码压缩
# - Tree Shaking
# - 代码分割
# - 资源优化

3. 预览阶段

# 本地预览
npm run preview
# - 模拟生产环境
# - 验证构建结果

⚙️ 核心配置

babel.config.json

{
  "presets": [
    ["@babel/preset-env", { "targets": "defaults" }],
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

.browserslistrc

defaults
not IE 11
maintained node versions

ESLint 配置

{
  "extends": ["eslint:recommended"],
  "env": {
    "browser": true,
    "es2021": true
  },
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "rules": {
    "no-unused-vars": "error"
  }
}

📊 构建优化

1. 代码分割

// 按需加载
const LazyComponent = React.lazy(() => import('./Component'))

// Webpack 分块
import(/* webpackChunkName: "user" */ './User')

2. Tree Shaking

3. 懒加载

// 路由懒加载
const Home = () => import('./pages/Home')

// 图片懒加载
<img loading="lazy" src="image.jpg" />

4. 缓存策略

📈 性能指标

Bundle 大小

构建速度

✅ 优缺点

优点

缺点

🎯 最佳实践

  1. 使用最新版本工具
  2. 合理配置代码分割
  3. 启用 Tree Shaking
  4. 压缩所有资源
  5. 使用 Source Map 调试
  6. 自动化构建流程
  7. CI/CD 集成
  8. 监控 Bundle 体积

📚 学习资源

🔗 相关链接