Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

vite-config 全面配置(持续更新)


细致全面的 vitejs 配置信息。涵盖了使用 vitejs 开发过程中大部分配置需求。

不建议直接拉取此项目作为模板,希望能按照此教程按需配置,或者复制 vite.config.js 增删配置,并自行安装所需依赖。

vue-cli4 配置见 vue-cli4-config 。

目录

√ 定义全局变量
√ 配置路径别名 alias
√ 配置代理 Proxy
√ 使用 TSX/JSX
√ SFC 支持 name 属性
√ ESlint 错误显示在浏览器中
√ 提供 externals
√ 提供全局 less、scss 变量
√ 按需加载 ElementPlus、Ant Design Vue
√ 生成雪碧图
√ CDN 加载类库
√ 打包分析
√ esbuild error

✅ 定义全局变量


使用 define 定义全局变量

通常情况下,在页面中会用到一些常量,而这些常量可能后期又会发生变更,那么这类常量就不能在代码中使用硬编码处理。

最基础的做法是在构建时生成全局常量,使用时引用全局常量。

vite.config.ts


  1. ``` js
  2. export default defineConfig({
  3.   define: {
  4.     INITIAL_COUNT: 10,
  5.   },
  6. })
  7. ```

在代码中使用:

  1. ``` vue
  2. const count = ref(INITIAL_COUNT);
  3. ```

使用 env 文件定义环境变量

Vite 使用dotenv 可以加载自定义的环境变量。

以下开发的 dev、stage、prod 三种环境为例。将新建四种 env 文件

  1. ``` shell
  2. .env         # 存放不同环境共用的环境变量,定义的变量将被各环境共享
  3. .env.dev     # 开发环境
  4. .env.stage   # 测试环境
  5. .env.prod    # 正式环境
  6. ```

.env


  1. ``` sh
  2. VITE_TOKEN_NAME = 'token'

  3. ```

.env.dev


  1. ``` sh
  2. NODE_ENV = development

  3. VITE_BASE_URL = http://wwww.demo.com/api

  4. VITE_BASE_PATH = /

  5. ```

.env.stage


  1. ``` shell
  2. NODE_ENV = production

  3. VITE_BASE_URL = http://wwww.stage.com/api

  4. VITE_BASE_PATH = /stage
  5. ```

.env.prod


  1. ``` shell
  2. NODE_ENV = production

  3. VITE_BASE_URL = http://wwww.prod.com/api

  4. VITE_BASE_PATH = /prod
  5. ```

vite 的--mode 选项,会读取指定的值匹配的环境变量,如运行 vite --mode dev 时,.env 和.env.dev 两个环境变量文件将被加载。

package.json


  1. ``` json
  2. "scripts": {
  3.   "dev": "vite --mode dev",
  4.   "stage": "vue-tsc --noEmit && vite build --mode stage",
  5.   "prod": "vue-tsc --noEmit && vite build --mode prod",
  6. },
  7. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import vue from '@vitejs/plugin-vue'

  4. export default ({ mode }: ConfigEnv): UserConfig => {
  5.   let plugins = [vue()]

  6.   return {
  7.     plugins,
  8.   }
  9. }
  10. ```

在 vite.config.ts 中可以使用 process.env 上挂载的变量。项目中,Vite 会在一个特殊的 import.meta.env 对象上暴露环境变量。默认以"VITE_"开头的变量,将被挂载在 import.meta.env 对象上。

在 src/env.d.ts 中添加以下信息,可实现环境变量代码自动提示:

  1. ``` ts
  2. interface ImportMetaEnv {
  3.   VITE_BASE_URL: string
  4. }

  5. interface ImportMeta {
  6.   readonly env: ImportMetaEnv
  7. }
  8. ```

▲ 回顶部

✅ 配置路径别名 alias


vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import path from 'path'

  4. const nodeResolve = (dir) => path.resolve(__dirname, '.', dir)

  5. export default ({ mode }: ConfigEnv): UserConfig => {
  6.   const resolve = {
  7.     alias: {
  8.       '@': nodeResolve('src'),
  9.       '~': nodeResolve('public'),
  10.     },
  11.   }

  12.   return {
  13.     resolve,
  14.   }
  15. }
  16. ```

使用 typescript 开发,如果出现找不到模块“path”或其相应的类型声明。则需要安装@types/node

  1. ``` shell
  2. npx pnpm i -D @types/node
  3. ```

修改 tsconfig.json 配置:

  1. ``` json
  2. {
  3.   "compilerOptions": {
  4.     "baseUrl": ".",
  5.     "importHelpers": true,
  6.     "skipLibCheck": true,
  7.     "allowSyntheticDefaultImports": true,
  8.     "paths": {
  9.       "@/*": ["src/*"]
  10.     }
  11.   }
  12. }
  13. ```

这样就可以使用'@'来替代相对路径对组件进行引用:

  1. ``` ts
  2. <script lang="ts">import HelloWorld from '@/components/HelloWorld.vue'</script>
  3. ```

也可以使用以下方式配置 alias:

  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import path from 'path'

  4. const nodeResolve = (dir) => path.resolve(__dirname, '.', dir)

  5. export default ({ mode }: ConfigEnv): UserConfig => {
  6.   return {
  7.     resolve: {
  8.       alias: [
  9.         {
  10.           find: /@\//,
  11.           replacement: `${nodeResolve('src')}/`,
  12.         },
  13.         {
  14.           find: /@comps\//,
  15.           replacement: `${nodeResolve('src/components')}/`,
  16.         },
  17.       ],
  18.     },
  19.   }
  20. }
  21. ```

▲ 回顶部

✅ 配置代理 Proxy


Vitejs 的开发服务器选项https://cn.vitejs.dev/config/#server-host

  1. ``` js
  2. export default ({ mode }: ConfigEnv): UserConfig => {
  3.   const server = {
  4.     host: '0.0.0.0',
  5.     port: 3000,
  6.     proxy: {
  7.       '/api': {
  8.         target: 'http://192.168.1.163:8081/',
  9.         changeOrigin: true,
  10.         rewrite: (url) => url.replace(/^\/api/, ''),
  11.       },
  12.     },
  13.   }

  14.   return {
  15.     server,
  16.   }
  17. }
  18. ```

target

实际的后端 api 地址。如请求/api/getUserInfo 会转发到http://192.168.1.163:8081/api/getUserInfo。

changeOrigin

是否改写 origin。设为 true,则请求 header 中 origin 将会与 target 配置项的域名一致。

rewrite

重写转发的请求链接。

▲ 回顶部

✅ 使用 TSX/JSX


@vitejs/plugin-vue-jsx 通过 HMR 提供 Vue 3 JSX 和 TSX 支持。

  1. ``` shell
  2. npx pnpm i @vitejs/plugin-vue-jsx
  3. ```

vite.config.ts


  1. ``` ts
  2. import vueJsx from '@vitejs/plugin-vue-jsx'

  3. export default ({ mode }: ConfigEnv): UserConfig => {
  4.   let plugins = [vueJsx()]

  5.   return {
  6.     plugins,
  7.   }
  8. }
  9. ```

修改 tsconfig.json 配置,使.tsx 中支持 JSX

  1. ``` json
  2. {
  3.   "compilerOptions": {
  4.     "jsx": "preserve" // .tsx中支持JSX
  5.   }
  6. }
  7. ```

▲ 回顶部

✅ SFC 支持 name 属性


vite-plugin-vue-setup-extend 支持<script setup>新增 name 属性

  1. ``` shell
  2. npx pnpm i -D vite-plugin-vue-setup-extend
  3. ```

vite.config.ts


  1. ``` ts
  2. import vueSetupExtend from 'vite-plugin-vue-setup-extend'

  3. export default ({ mode }: ConfigEnv): UserConfig => {
  4.   let plugins = [vueSetupExtend()]

  5.   return {
  6.     plugins,
  7.   }
  8. }
  9. ```

▲ 回顶部

✅ ESlint 错误显示在浏览器中


vite-plugin-eslint

  1. ``` shell
  2. npx pnpm i -D vite-plugin-eslint
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import eslintPlugin from 'vite-plugin-eslint'

  4. export default ({ mode }: ConfigEnv): UserConfig => {
  5.   const IS_PROD = ['prod', 'production'].includes(mode)

  6.   let plugins = []

  7.   if (!IS_PROD) {
  8.     plugins = [
  9.       ...plugins,
  10.       eslintPlugin({
  11.         cache: false,
  12.         include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx'],
  13.       }),
  14.     ]
  15.   }

  16.   return {
  17.     plugins,
  18.   }
  19. }
  20. ```

▲ 回顶部

✅ 提供 externals


vite-plugin-externals :为 Vite 提供 commonjs 外部支持

  1. ``` shell
  2. npx pnpm i -D vite-plugin-externals
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import { viteExternalsPlugin } from 'vite-plugin-externals'

  4. export default ({ mode }: ConfigEnv): UserConfig => {
  5.   const IS_PROD = ['prod', 'production'].includes(mode)

  6.   let plugins = []

  7.   if (IS_PROD) {
  8.     plugins = [
  9.       ...plugins,
  10.       viteExternalsPlugin({
  11.         vue: 'Vue',
  12.         react: 'React',
  13.         'react-dom': 'ReactDOM',
  14.         // value support chain, tranform to window['React']['lazy']
  15.         lazy: ['React', 'lazy'],
  16.       }),
  17.     ]
  18.   }

  19.   return {
  20.     plugins,
  21.   }
  22. }
  23. ```

▲ 回顶部

✅ 提供全局 less、scss 变量


提供全局 less 变量

直接提供变量

  1. ``` ts
  2. export default ({ mode }: ConfigEnv): UserConfig => {
  3.   const css = {
  4.     preprocessorOptions: {
  5.       less: {
  6.         additionalData: `@injectedColor: red;`,
  7.         javascriptEnabled: true,
  8.       },
  9.     },
  10.   }
  11.   return {
  12.     css,
  13.   }
  14. }
  15. ```

通过导入 less 文件提供变量

  1. ``` ts
  2. export default ({ mode }: ConfigEnv): UserConfig => {
  3.   const css = {
  4.     preprocessorOptions: {
  5.       less: {
  6.         additionalData: '@import "@/assets/less/variables.less";',
  7.         javascriptEnabled: true,
  8.       },
  9.     },
  10.   }

  11.   return {
  12.     css,
  13.   }
  14. }
  15. ```

提供全局 scss 变量

直接提供变量

  1. ``` ts
  2. export default ({ mode }: ConfigEnv): UserConfig => {
  3.   const css = {
  4.     preprocessorOptions: {
  5.       less: {
  6.         additionalData: `$injectedColor: orange;`,
  7.         javascriptEnabled: true,
  8.       },
  9.     },
  10.   }
  11.   return {
  12.     css,
  13.   }
  14. }
  15. ```

通过导入 scss 文件提供变量

  1. ``` ts
  2. export default ({ mode }: ConfigEnv): UserConfig => {
  3.   const css = {
  4.     preprocessorOptions: {
  5.       scss: {
  6.         additionalData: `@import "@/assets/scss/variables.scss";`,
  7.         javascriptEnabled: true,
  8.       },
  9.     },
  10.   }

  11.   return {
  12.     css,
  13.   }
  14. }
  15. ```

▲ 回顶部

✅ 按需加载 ElementPlus、Ant Design Vue


unplugin-vue-components

按需引入 ElementPlus

unplugin-element-plus 为 Element Plus 按需引入样式。

  1. ``` shell
  2. npx pnpm i -D unplugin-vue-components unplugin-element-plus
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'

  3. import Components from 'unplugin-vue-components/vite'
  4. import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
  5. import ElementPlus from 'unplugin-element-plus/vite'

  6. export default ({ mode }: ConfigEnv): UserConfig => {
  7.   let plugins = [
  8.     Components({
  9.       resolvers: [ElementPlusResolver()],
  10.     }),
  11.     ElementPlus({}),
  12.   ]

  13.   return {
  14.     plugins,
  15.   }
  16. }
  17. ```

按需引入 Ant Design Vue

  1. ``` shell
  2. npx pnpm i -D unplugin-vue-components
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'

  3. import Components from 'unplugin-vue-components/vite'
  4. import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

  5. export default ({ mode }: ConfigEnv): UserConfig => {
  6.   let plugins = [
  7.     Components({
  8.       resolvers: [AntDesignVueResolver()],
  9.     }),
  10.   ]
  11.   return {
  12.     plugins,
  13.   }
  14. }
  15. ```

▲ 回顶部

✅ 生成雪碧图


vite-plugin-svg-icons

  1. ``` shell
  2. npx pnpm i -D vite-plugin-svg-icons
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import viteSvgIcons from 'vite-plugin-svg-icons'

  4. import path from 'path'

  5. const nodeResolve = (dir) => path.resolve(__dirname, dir)

  6. export default ({ mode }: ConfigEnv): UserConfig => {
  7.   let plugins = [
  8.     viteSvgIcons({
  9.       // 指定需要缓存的图标文件夹
  10.       iconDirs: [nodeResolve('icons')],
  11.       // 指定symbolId格式
  12.       symbolId: 'icon-[dir]-[name]',
  13.       // 是否压缩
  14.       svgoOptions: true,
  15.     }),
  16.   ]

  17.   return {
  18.     plugins,
  19.   }
  20. }
  21. ```

使用方式见https://github.com/anncwb/vite-plugin-svg-icons/blob/main/README.zh_CN.md

▲ 回顶部

✅ CDN 加载类库


vite-plugin-cdn-import

  1. ``` shell
  2. npx pnpm i -D vite-plugin-cdn-import
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import importToCDN from 'vite-plugin-cdn-import'

  4. export default ({ mode }: ConfigEnv): UserConfig => {
  5.   const IS_PROD = ['prod', 'production'].includes(mode)

  6.   let plugins = []

  7.   if (IS_PROD) {
  8.     plugins = [
  9.       ...plugins,
  10.       importToCDN({
  11.         modules: [
  12.           {
  13.             name: 'cesium',
  14.             var: 'Cesium',
  15.             path: `https://cesium.com/downloads/cesiumjs/releases/1.88/Build/Cesium/Cesium.js`,
  16.           },
  17.           {
  18.             name: 'widgets',
  19.             path: `https://cesium.com/downloads/cesiumjs/releases/1.88/Build/Cesium/Widgets/widgets.css`,
  20.           },
  21.         ],
  22.       }),
  23.     ]
  24.   }

  25.   return {
  26.     plugins,
  27.   }
  28. }
  29. ```

▲ 回顶部

✅ 打包分析


rollup-plugin-visualizer

  1. ``` shell
  2. npx pnpm i -D rollup-plugin-visualizer
  3. ```

vite.config.ts


  1. ``` ts
  2. import { UserConfig, ConfigEnv, loadEnv } from 'vite'
  3. import { visualizer } from 'rollup-plugin-visualizer'

  4. export default ({ mode }: ConfigEnv): UserConfig => {
  5.   const IS_PROD = ['prod', 'production'].includes(mode)

  6.   let plugins = []

  7.   if (IS_PROD) {
  8.     plugins = [...plugins, visualizer()]
  9.   }

  10.   return {
  11.     plugins,
  12.   }
  13. }
  14. ```

▲ 回顶部

✅ esbuild error


  1. ``` shell
  2. Error: spawn D:\github\vite-config\node_modules\esbuild\esbuild.exe ENOENT
  3.     at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
  4.     at onErrorNT (node:internal/child_process:480:16)
  5.     at processTicksAndRejections (node:internal/process/task_queues:83:21)
  6. Emitted 'error' event on ChildProcess instance at:
  7.     at Process.ChildProcess._handle.onexit (node:internal/child_process:288:12)
  8.     at onErrorNT (node:internal/child_process:480:16)
  9.     at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  10. ```

  1. ``` shell
  2. node ./node_modules/esbuild/install.js
  3. ```

▲ 回顶部
Last Updated: 2023-05-23 11:11:51