文章目录
正文
1. Vue CLI 工程化配置
1.1 Vue CLI 简介与安装
Vue CLI 是基于 webpack 构建的标准化工具链,用于快速搭建 Vue.js 项目。
# 安装 Vue CLI
npm install -g @vue/cli
# 查看版本
vue --version
# 创建项目
vue create my-project
1.2 项目结构
my-project/
├── node_modules/ # 依赖包
├── public/ # 静态资源
│ ├── favicon.ico
│ └── index.html # HTML 模板
├── src/ # 源代码
│ ├── assets/ # 资源文件
│ ├── components/ # 组件
│ ├── views/ # 视图
│ ├── App.vue # 根组件
│ ├── main.js # 入口文件
│ ├── router.js # 路由配置
│ └── store.js # 状态管理
├── .browserslistrc # 浏览器兼容配置
├── .eslintrc.js # ESLint 配置
├── babel.config.js # Babel 配置
├── package.json # 项目依赖
└── vue.config.js # Vue CLI 配置
1.3 vue.config.js 配置详解
module.exports = {
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV !== 'production',
productionSourceMap: false,
devServer: {
port: 8080,
open: true,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: { '^/api': '' }
}
}
},
configureWebpack: {
// webpack 配置
},
chainWebpack: config => {
// 链式 webpack 配置
}
}
1.4 环境变量配置
# .env.development
VUE_APP_API_URL=http://dev-api.example.com
# .env.production
VUE_APP_API_URL=http://api.example.com
在代码中使用:
console.log(process.env.VUE_APP_API_URL)
2. Vite 工程化配置
2.1 Vite 简介与安装
Vite 是下一代前端构建工具,提供更快的开发服务器启动和即时的模块热更新。
# 使用 npm
npm create vite@latest my-vite-project -- --template vue
# 使用 yarn
yarn create vite my-vite-project --template vue
# 使用 pnpm
pnpm create vite my-vite-project --template vue
2.2 项目结构
my-vite-project/
├── node_modules/ # 依赖包
├── public/ # 静态资源
│ └── favicon.ico
├── src/ # 源代码
│ ├── assets/ # 资源文件
│ ├── components/ # 组件
│ ├── App.vue # 根组件
│ └── main.js # 入口文件
├── .gitignore # Git 忽略文件
├── index.html # HTML 入口
├── package.json # 项目依赖
├── vite.config.js # Vite 配置
└── README.md # 项目说明
2.3 vite.config.js 配置详解
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
},
build: {
outDir: 'dist',
assetsDir: 'assets',
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
}
})
2.4 环境变量配置
# .env
VITE_APP_TITLE=My App
# .env.development
VITE_APP_API_URL=http://dev-api.example.com
# .env.production
VITE_APP_API_URL=http://api.example.com
在代码中使用:
console.log(import.meta.env.VITE_APP_API_URL)
3. Vue CLI 与 Vite 性能对比
3.1 启动时间对比
工具 | 冷启动时间 | 热启动时间 |
---|---|---|
Vue CLI | 8-15秒 | 2-5秒 |
Vite | 300ms以内 | 100ms以内 |
3.2 构建时间对比
工具 | 小型项目 | 中型项目 | 大型项目 |
---|---|---|---|
Vue CLI | 10-20秒 | 30-60秒 | 1-3分钟 |
Vite | 5-10秒 | 15-30秒 | 30-90秒 |
3.3 HMR(热更新)速度对比
工具 | 组件更新 | 样式更新 |
---|---|---|
Vue CLI | 300-800ms | 200-500ms |
Vite | 50-100ms | 20-50ms |
4. 迁移策略:从 Vue CLI 到 Vite
4.1 依赖调整
// package.json
{
"devDependencies": {
- "@vue/cli-service": "^5.0.0",
+ "vite": "^4.0.0",
+ "@vitejs/plugin-vue": "^4.0.0"
}
}
4.2 配置文件转换
// 从 vue.config.js
module.exports = {
publicPath: '/',
outputDir: 'dist',
devServer: {
port: 8080
}
}
// 转换为 vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
base: '/',
build: {
outDir: 'dist'
},
server: {
port: 8080
}
})
4.3 入口文件调整
<!-- 新增 index.html 作为入口 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
4.4 环境变量前缀修改
- VUE_APP_API_URL=http://api.example.com
+ VITE_API_URL=http://api.example.com
// 在代码中
- console.log(process.env.VUE_APP_API_URL)
+ console.log(import.meta.env.VITE_API_URL)
5. 高级配置与优化
5.1 构建优化
// vite.config.js
export default defineConfig({
build: {
// 启用/禁用 CSS 代码拆分
cssCodeSplit: true,
// 构建后是否生成 source map 文件
sourcemap: false,
// 指定生成静态资源的存放路径
assetsDir: 'assets',
// 小于此阈值的导入或引用资源将内联为 base64 编码
assetsInlineLimit: 4096,
// 启用/禁用 brotli 压缩大小报告
brotliSize: true,
// chunk 大小警告的限制
chunkSizeWarningLimit: 500,
// 自定义底层的 Rollup 打包配置
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'vue-router', 'vuex'],
ui: ['element-plus']
}
}
}
}
})
5.2 预构建依赖优化
// vite.config.js
export default defineConfig({
optimizeDeps: {
// 预构建的依赖项
include: ['vue', 'vue-router', 'vuex', 'axios'],
// 排除预构建的依赖项
exclude: ['your-package'],
// 强制预构建链接的包
entries: [],
// 启用依赖项预构建的缓存
force: true
}
})
5.3 CSS 预处理器配置
// vite.config.js
export default defineConfig({
css: {
// 是否开启 CSS 的 source map
devSourcemap: true,
// CSS 预处理器配置
preprocessorOptions: {
scss: {
additionalData: `
@import "@/styles/variables.scss";
@import "@/styles/mixins.scss";
`
},
less: {
javascriptEnabled: true,
modifyVars: {
'@primary-color': '#1890ff'
}
}
},
// PostCSS 配置
postcss: {
plugins: [
require('autoprefixer'),
require('postcss-preset-env')
]
}
}
})
5.4 多页面应用配置
// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
admin: path.resolve(__dirname, 'admin.html')
}
}
}
})
6. 插件系统
6.1 常用 Vue CLI 插件
# 添加 TypeScript 支持
vue add typescript
# 添加 Vuex 支持
vue add vuex
# 添加 Vue Router 支持
vue add router
# 添加 ESLint 支持
vue add eslint
6.2 常用 Vite 插件
// vite.config.js
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import legacy from '@vitejs/plugin-legacy'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
vue(),
vueJsx(),
legacy({
targets: ['defaults', 'not IE 11']
}),
Components({
resolvers: [ElementPlusResolver()]
}),
AutoImport({
imports: ['vue', 'vue-router', 'vuex'],
dts: 'src/auto-imports.d.ts'
})
]
})
7. 部署配置
7.1 基本路径配置
// Vue CLI (vue.config.js)
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/my-app/'
: '/'
}
// Vite (vite.config.js)
export default defineConfig({
base: process.env.NODE_ENV === 'production'
? '/my-app/'
: '/'
})
7.2 静态资源处理
// Vue CLI (vue.config.js)
module.exports = {
assetsDir: 'static',
productionSourceMap: false
}
// Vite (vite.config.js)
export default defineConfig({
build: {
assetsDir: 'static',
sourcemap: false
}
})
7.3 CDN 配置
// Vue CLI (vue.config.js)
module.exports = {
chainWebpack: config => {
config.plugin('html')
.tap(args => {
args[0].cdn = {
css: ['https://cdn.jsdelivr.net/npm/element-plus@2.2.0/dist/index.css'],
js: ['https://cdn.jsdelivr.net/npm/vue@3.2.37/dist/vue.global.js']
}
return args
})
},
configureWebpack: {
externals: {
vue: 'Vue',
'element-plus': 'ElementPlus'
}
}
}
// Vite (vite.config.js)
export default defineConfig({
build: {
rollupOptions: {
external: ['vue', 'element-plus'],
output: {
globals: {
vue: 'Vue',
'element-plus': 'ElementPlus'
}
}
}
}
})
结语
感谢您的阅读!期待您的一键三连!欢迎指正!