前端工程化方向
前端工程化的主要领域和实践方案
问题
前端工程化包含哪些方向?各方向的主流方案是什么?
解答
1. 模块化
// CommonJS (Node.js)
const lodash = require('lodash');
module.exports = { foo: 'bar' };
// ES Modules (浏览器/现代 Node.js)
import lodash from 'lodash';
export const foo = 'bar';
2. 构建工具
| 工具 | 特点 | 适用场景 |
|---|---|---|
| Webpack | 功能全面,生态丰富 | 大型应用 |
| Vite | 开发快,基于 ESM | 现代项目首选 |
| Rollup | 产物干净 | 库开发 |
| esbuild | 极速编译 | 底层工具 |
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
build: {
rollupOptions: {
output: {
// 分包策略
manualChunks: {
vendor: ['react', 'react-dom'],
},
},
},
},
});
3. 代码规范
// .eslintrc.js
module.exports = {
extends: ['eslint:recommended', 'prettier'],
rules: {
'no-console': 'warn',
'no-unused-vars': 'error',
},
};
// .prettierrc
{
"semi": true,
"singleQuote": true,
"tabWidth": 2
}
// package.json - lint-staged 配置
{
"lint-staged": {
"*.{js,ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{css,scss}": ["prettier --write"]
}
}
4. 包管理
# pnpm - 推荐,节省磁盘空间,安装快
pnpm install
# Monorepo 管理
pnpm init
# pnpm-workspace.yaml
packages:
- 'packages/*'
5. 自动化测试
// Jest 单元测试
describe('add', () => {
it('should return sum of two numbers', () => {
expect(add(1, 2)).toBe(3);
});
});
// Playwright E2E 测试
test('login flow', async ({ page }) => {
await page.goto('/login');
await page.fill('[name="email"]', 'test@example.com');
await page.fill('[name="password"]', '123456');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/dashboard');
});
6. CI/CD
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- run: pnpm install
- run: pnpm lint
- run: pnpm test
- run: pnpm build
7. 性能监控
// Web Vitals 监控
import { onCLS, onFID, onLCP } from 'web-vitals';
onCLS(console.log); // 累积布局偏移
onFID(console.log); // 首次输入延迟
onLCP(console.log); // 最大内容绘制
关键点
- 模块化:ES Modules 是标准,CommonJS 用于 Node.js
- 构建工具:新项目用 Vite,库用 Rollup,复杂场景用 Webpack
- 代码规范:ESLint + Prettier + lint-staged + husky 组合
- 包管理:pnpm 是当前最佳选择,原生支持 Monorepo
- 测试:Jest/Vitest 做单测,Playwright 做 E2E
- CI/CD:GitHub Actions 是主流,自动化 lint、test、build、deploy
目录