vue3笔记(18-1)使用vite进行前端构建

之前的项目大多使用vue-cli搭建,感觉打包时间略长,随着项目体积增大,协作人数增加,尝试使用vite重新进行构建,并建立前端规范。

基础知识

  1. 开箱即用,API高度可扩展性
  2. MHR速度快
  3. 一套构建指令,使用Rollup打包代码,预配置,输出高度优化的静态资源

项目初始化

使用vite创建项目,并根据需求选择相应配置:

1
npm create vite@latest

实践中已使用的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueJsx from '@vitejs/plugin-vue-jsx'
import { resolve } from 'path'
import EslintPlugin from 'vite-plugin-eslint'
import AutoImport from 'unplugin-auto-import/vite'
import DefineOptions from 'unplugin-vue-define-options/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import'

export default defineConfig({
plugins: [
vue(),
VueJsx(),
Components({
// 要搜索组件的目录的相对路径
dirs: ['src/components'],
extensions: ['vue'],
// 搜索子目录
deep: true,
// 生成自定义 `auto-components.d.ts` 全局声明
dts: 'src/types/auto-components.d.ts',
include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/],
// 自定义组件的解析器
resolvers: [ElementPlusResolver()],
exclude: [/[\\/]node_modules[\\/]/]
}),
AutoImport({
// 生成自定义 `auto-components.d.ts` 全局声明
dts: 'src/types/auto-imports.d.ts',
include: [/\.[tj]sx?$/, /\.vue$/],
// 自动引入的api从这里找
imports: ['vue', 'vue-router'],
resolvers: [
ElementPlusResolver() // 自动导入Element-Plus的Api
],
eslintrc: {
enabled: false,
filepath: './.eslintrc-auto-import.json',
globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
}
}),
createStyleImportPlugin({
resolves: [ElementPlusResolve()],
libs: [{
libraryName: 'element-plus',
esModule: true,
resolveStyle: (name) => {
return `element-plus/es/components/${name.substring(3)}/style/css`
}
}]
}),
EslintPlugin({
cache: false,
include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx'] // 检查的文件
}),
DefineOptions()
],
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/assets/scss/index.scss";`
}
}
},
resolve: {
alias: {
'@': resolve(__dirname, './src')
}
},
build: {
minify: 'terser',
outDir: 'dist',
sourcemap: 'inline',
terserOptions: {
compress: {
drop_debugger: true,
drop_console: false
}
}
},
server: {
host: 'localhost',
port: 8080,
open: true, //配置浏览器自动访问
headers: {
'Access-Control-Allow-Origin': '*'
},
proxy: {
'/api': {
target: 'http://',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, 'api')
}
},
hmr: true,
}
})

附录
Vite官方文档


vue3笔记(18-1)使用vite进行前端构建
https://guoningyan.com/2023/03/16/vue3笔记(18-1)使用vite进行前端构建/
作者
Ningyan Guo
发布于
2023年3月16日
许可协议