浅析前端工程化
前言
一个前端项目为什么会有那么多配置文件?ESLint、Prettier、husky、commitlint、GitHub Actions——它们分别解决什么问题,又如何协同工作?
本文从四个维度拆解前端工程化:模块化、组件化、规范化、自动化,并在最后给出一个可运行的 Vue 项目示例。
四维拆解
模块化解决的是代码如何拆分和引用的问题。JS 有 ES Module,CSS 有 scoped 和 CSS Modules,静态资源通过 import 引入。模块化的核心价值不在于"拆",而在于拆完之后依赖关系清晰、边界明确。
组件化是在模块化之上,从 UI 设计层面做拆分。一个 .vue 文件封装了模板、逻辑和样式,对外暴露 props 和 events,对内隐藏实现细节。和模块化的区别:模块化面向文件,组件化面向界面。
规范化是提前约定的执行标准。编码规范(ESLint + Prettier)、提交规范(commitlint)、目录结构规范——没有规范,工具再多也只是加速制造混乱。
自动化把编译、测试、部署交给机器。Vite 负责构建,vitest 跑测试,GitHub Actions 串联 CI/CD 流程。自动化的前提是前三步已经做到位——没有模块化和规范化,自动化毫无意义。
示例:Vue 项目工程化实践
项目初始化
npm create vue@latest
脚手架已经集成了 ESLint、Prettier、Vite、vitest 的可选项,勾选后即可获得一套可用的工程化配置。
模块化
- JS:
package.json中type: "module"开启 ESM - CSS:
<style scoped>通过 PostCSS 给元素加data-v-xxx属性实现样式隔离;需要更彻底的隔离可使用 CSS Modules - 静态资源:Vite 支持
import imgUrl from './img.png'直接引用,构建时自动处理路径和哈希
组件化
Vue 的组件模型是树状结构——页面是根组件,向下拆分为功能组件,再拆为基础组件。每个 .vue 文件是一个独立单元:
- 有自己的状态和行为
- 通过 props 接收输入,通过 emits 输出变更
- 可以被单独测试和复用
提交规范:husky + commitlint
npm install --save-dev husky
npx husky init
在 .husky/pre-commit 中配置 npm run lint,每次提交前自动执行代码检查。
npm i @commitlint/config-conventional @commitlint/cli -D
创建 .commitlintrc.json:
{ "extends": ["@commitlint/config-conventional"] }
在 .husky/commit-msg 中写入:
npx --no-install commitlint --edit "$1"
此后提交信息必须符合约定格式(feat:、fix:、chore: 等),不规范则拒绝提交。
CI/CD:GitHub Actions
在 .github/workflows/ci.yml 中配置自动测试:
name: CI
on:
push:
branches: ['**']
pull_request:
branches: ['**']
jobs:
linter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run lint
tests:
needs: linter
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run test:unit
所有分支的 push 和 PR 都会触发 lint 和 test。tests 依赖 linter 通过后执行。
cd.yml 负责部署——构建完成后通过 SSH 将产物推送到服务器:
name: CD
on:
push:
branches: ['master']
jobs:
deploy:
needs: ci
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci --ignore-scripts
- run: npm run build
- name: deploy
uses: cross-the-world/ssh-scp-ssh-pipelines@latest
with:
host: ${{ secrets.DC_HOST }}
user: ${{ secrets.DC_USER }}
pass: ${{ secrets.DC_PASS }}
scp: './dist/* => /www/wwwroot/app/'
last_ssh: |
nginx -t && nginx -s reload
敏感信息(HOST、USER、PASS)通过 GitHub Secrets 配置,不写入代码仓库。
小结
前端工程化的本质不是配配置文件,而是建立一套可复制的交付标准。模块化管代码结构,组件化管 UI 复用,规范化管协作约束,自动化管流程效率——四个维度到位,项目才能真正规模化。