14-Vue2 项目构建与工程化

14-Vue2 项目构建与工程化 Vue2 项目构建与工程化现代前端开发离不开工程化工具链的支持。本章将系统讲解 Vue CLI 的使用、Webpack 配置、环境变量管理、代码规范以及打包优化策略帮助你构建生产级的 Vue 项目。一、前言随着前端项目规模的增长我们需要解决以下问题如何快速创建标准化项目结构如何管理多环境配置如何自动化代码检查和格式化如何优化打包体积和加载性能Vue CLI 是 Vue 生态的标准工具链围绕 Webpack 封装了一套完整的工程化方案。Vue 工程化项目脚手架构建配置代码规范性能优化Vue CLIWebpack环境变量ESLintPrettier代码分割压缩优化二、Vue CLI 脚手架2.1 安装与创建项目# 全局安装 Vue CLInpminstall-gvue/cli# 创建项目命令行交互vue create my-project# 使用预设快速创建vue create my-project--presetdefault2.2 预设配置选项? Please pick a preset: Default([Vue2]babel, eslint)Default(Vue3)([Vue3]babel, eslint)Manuallyselectfeatures# 手动选择? Check the features neededforyour project: ◉ Babel# JavaScript 编译器◉ TypeScript# 类型系统◉ Progressive Web App# PWA 支持◉ Router# Vue Router◉ Vuex# 状态管理◉ CSS Pre-processors# CSS 预处理器◉ Linter / Formatter# 代码规范◉ Unit Testing# 单元测试◉ E2E Testing# E2E 测试2.3 项目结构my-project/ ├── public/ # 静态资源不经过 Webpack 处理 │ ├── index.html │ └── favicon.ico ├── src/ │ ├── assets/ # 静态资源经过 Webpack 处理 │ ├── components/ # 公共组件 │ ├── views/ # 页面组件 │ ├── router/ # 路由配置 │ ├── store/ # Vuex 配置 │ ├── App.vue # 根组件 │ └── main.js # 入口文件 ├── .env # 环境变量 ├── .eslintrc.js # ESLint 配置 ├── babel.config.js # Babel 配置 ├── vue.config.js # Vue CLI 配置 └── package.json三、Vue CLI 配置3.1 vue.config.js 基础配置// vue.config.jsconst{defineConfig}require(vue/cli-service);module.exportsdefineConfig({// 基本路径publicPath:process.env.NODE_ENVproduction?/app/:/,// 输出目录outputDir:dist,// 静态资源目录assetsDir:static,// 是否使用运行时编译器runtimeCompiler:false,// 生产环境 source mapproductionSourceMap:false,// 开发服务器配置devServer:{port:8080,open:true,proxy:{/api:{target:http://localhost:3000,changeOrigin:true,pathRewrite:{^/api:}}}},// Webpack 配置configureWebpack:{plugins:[// 自定义插件]},// 链式 Webpack 配置chainWebpack:config{config.plugin(html).tap(args{args[0].titleMy App;returnargs;});}});3.2 链式配置详解// vue.config.jsmodule.exports{chainWebpack:config{// 修改已有 Loader 选项config.module.rule(vue).use(vue-loader).tap(options{return{...options,hotReload:false};});// 添加新 Loaderconfig.module.rule(markdown).test(/\.md$/).use(html-loader).loader(html-loader).end().use(markdown-loader).loader(markdown-loader);// 修改插件选项config.plugin(define).tap(args{args[0][process.env].API_URLJSON.stringify(process.env.API_URL);returnargs;});// 开发环境与生产环境不同配置config.when(process.env.NODE_ENVproduction,config{config.plugin(compression).use(require(compression-webpack-plugin),[{algorithm:gzip}]);});}};四、环境变量管理4.1 环境变量文件Vue CLI 支持通过.env文件管理环境变量# .env # 所有环境加载# .env.local # 所有环境加载不提交到 Git# .env.[mode] # 只在指定模式加载# .env.[mode].local # 只在指定模式加载不提交到 Git# .envVUE_APP_TITLEMy ApplicationVUE_APP_API_URL/api# .env.developmentVUE_APP_API_URLhttp://localhost:3000NODE_ENVdevelopment# .env.productionVUE_APP_API_URLhttps://api.example.comNODE_ENVproduction4.2 使用环境变量// 代码中使用constapiUrlprocess.env.VUE_APP_API_URL;constisDevprocess.env.NODE_ENVdevelopment;// template 中使用p{{$envTitle}}/p注意只有以VUE_APP_开头的变量才会被注入到客户端代码中。五、代码规范5.1 ESLint 配置// .eslintrc.jsmodule.exports{root:true,env:{node:true},extends:[plugin:vue/essential,eslint:recommended],parserOptions:{parser:babel/eslint-parser,requireConfigFile:false},rules:{// 自定义规则no-console:process.env.NODE_ENVproduction?warn:off,no-debugger:process.env.NODE_ENVproduction?warn:off,vue/multi-word-component-names:off,indent:[error,4],quotes:[error,single],semi:[error,always]}};5.2 Prettier 集成// .prettierrc{semi:true,singleQuote:true,tabWidth:4,trailingComma:none,printWidth:100,arrowParens:avoid}// 安装依赖npm install-Deslint-plugin-prettier eslint-config-prettier prettier// .eslintrc.js - 集成 Prettiermodule.exports{extends:[plugin:vue/essential,eslint:recommended,plugin:prettier/recommended// 添加这一行]};5.3 提交前检查npminstall-Dlint-staged husky// package.json{lint-staged:{*.{js,vue}:[eslint --fix,git add]},husky:{hooks:{pre-commit:lint-staged}}}六、打包优化6.1 代码分割// 路由懒加载constHome()import(/* webpackChunkName: home */../views/Home.vue);// 组件懒加载constHeavyComponent()import(/* webpackChunkName: heavy */../components/Heavy.vue);// 异步加载库asyncfunctionloadChart(){constechartsawaitimport(echarts);returnecharts;}6.2 优化策略// vue.config.jsmodule.exports{configureWebpack:config{if(process.env.NODE_ENVproduction){// 分离第三方库config.optimization.splitChunks{chunks:all,cacheGroups:{vendor:{name:chunk-vendors,test:/[\\/]node_modules[\\/]/,priority:10,chunks:initial},common:{name:chunk-common,minChunks:2,priority:5,chunks:initial,reuseExistingChunk:true}}};// 运行时分离config.optimization.runtimeChunk{name:runtime};}}};6.3 体积分析与优化# 分析打包体积npmrun build ----report# 或使用 webpack-bundle-analyzernpminstall-Dwebpack-bundle-analyzer// vue.config.jsconst{BundleAnalyzerPlugin}require(webpack-bundle-analyzer);module.exports{chainWebpack:config{if(process.env.ANALYZE){config.plugin(analyzer).use(BundleAnalyzerPlugin);}}};6.4 Gzip 压缩npminstall-Dcompression-webpack-plugin// vue.config.jsconstCompressionPluginrequire(compression-webpack-plugin);module.exports{configureWebpack:{plugins:[newCompressionPlugin({algorithm:gzip,test:/\.(js|css|html|svg)$/,threshold:10240,minRatio:0.8})]}};七、多页面应用配置// vue.config.jsmodule.exports{pages:{index:{entry:src/main.js,template:public/index.html,filename:index.html,title:首页,chunks:[chunk-vendors,chunk-common,index]},admin:{entry:src/admin/main.js,template:public/admin.html,filename:admin.html,title:管理后台,chunks:[chunk-vendors,chunk-common,admin]}}};八、现代模式构建Vue CLI 支持为现代浏览器构建更小的包# 现代模式生成两套 bundle现代浏览器用 ES modules旧浏览器用传统方式vue-cli-service build--modern!-- 自动注入到 index.html --scripttypemodulesrc/js/app.js/scriptscriptnomodulesrc/js/app-legacy.js/script九、Docker 部署配置# Dockerfile FROM node:16-alpine as builder WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build FROM nginx:alpine COPY --frombuilder /app/dist /usr/share/nginx/html COPY nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80# nginx.conf server { listen 80; location / { root /usr/share/nginx/html; index index.html; try_files $uri $uri/ /index.html; } location /api { proxy_pass http://backend:3000; } }十、总结知识点核心内容Vue CLIvue create创建项目vue.config.js配置环境变量.env文件VUE_APP_前缀ESLint/Prettier代码规范与格式化代码分割import()懒加载splitChunks 优化体积分析webpack-bundle-analyzer现代模式--modern构建下一章我们将进入 Vue2项目实战综合运用所学知识完成一个完整的后台管理系统。十一、练习使用 Vue CLI 创建一个新项目配置 TypeScript Vue Router Vuex配置 ESLint Prettier在提交前自动格式化代码为项目配置路由懒加载和代码分割分析打包体积变化编写一个多环境配置文件开发/测试/生产在不同环境显示不同 API 地址