前端工程化:从零搭建现代开发环境
新项目启动,开发环境搭建是第一步。记录一套成熟方案。
工具链选择
构建工具
| 工具 | 特点 | 推荐场景 |
|---|---|---|
| Vite | 快、现代 | 新项目首选 |
| Webpack | 成熟、生态好 | 复杂需求 |
| Rspack | Webpack 兼容、更快 | Webpack 项目迁移 |
| esbuild | 极快 | 库开发、简单项目 |
代码规范
| 工具 | 用途 |
|---|---|
| ESLint | 代码检查 |
| Prettier | 代码格式化 |
| Stylelint | 样式检查 |
| Commitlint | 提交信息规范 |
项目结构
project/
├── src/
│ ├── components/
│ ├── hooks/
│ ├── utils/
│ ├── api/
│ ├── styles/
│ ├── types/
│ ├── pages/
│ ├── App.tsx
│ └── main.tsx
├── public/
├── tests/
├── scripts/
├── .vscode/
├── package.json
├── tsconfig.json
├── vite.config.ts
├── eslint.config.js
└── .prettierrc
TypeScript 配置
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
ESLint 配置
// eslint.config.js
import js from '@eslint/js';
import typescript from '@typescript-eslint/eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';
import react from 'eslint-plugin-react';
import reactHooks from 'eslint-plugin-react-hooks';
import prettier from 'eslint-config-prettier';
export default [
js.configs.recommended,
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: typescriptParser,
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
},
plugins: {
'@typescript-eslint': typescript,
'react': react,
'react-hooks': reactHooks,
},
rules: {
...typescript.configs.recommended.rules,
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
settings: {
react: {
version: 'detect',
},
},
},
prettier,
];
Vite 配置
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
sourcemap: true,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
utils: ['lodash', 'dayjs'],
},
},
},
},
});
Git Hooks
husky
npm install husky -D
npx husky init
# .husky/pre-commit
npm run lint
npm run test
# .husky/commit-msg
npx commitlint --edit $1
commitlint
// commitlint.config.js
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore'],
],
},
};
VS Code 配置
// .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
// .vscode/extensions.json
{
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"ms-vscode.vscode-typescript-next"
]
}
NPM Scripts
{
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "eslint src --ext .ts,.tsx",
"lint:fix": "eslint src --ext .ts,.tsx --fix",
"format": "prettier --write \"src/**/*.{ts,tsx,css}\"",
"test": "vitest",
"test:coverage": "vitest --coverage",
"type-check": "tsc --noEmit",
"prepare": "husky"
}
}
环境变量
# .env
VITE_API_BASE_URL=http://localhost:8080/api
# .env.development
VITE_API_BASE_URL=http://dev-api.example.com
# .env.production
VITE_API_BASE_URL=https://api.example.com
// src/config.ts
export const config = {
apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
};
CI/CD 配置
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
lint-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run type-check
- run: npm run test
- run: npm run build
常用 VS Code 插件
| 插件 | 用途 |
|---|---|
| ESLint | 代码检查 |
| Prettier | 代码格式化 |
| GitLens | Git 增强 |
| Error Lens | 行内错误提示 |
| Auto Rename Tag | 标签重命名 |
| Path Intellisense | 路径提示 |
总结
好的开发环境:
- 统一配置:团队配置一致
- 自动化:格式化、检查自动化
- 类型安全:TypeScript 严格模式
- 快速反馈:ESLint 即时提示
花时间搭建好环境,后续开发效率翻倍。