配置 Vite
当从命令行运行 vite 时,Vite 会自动尝试解析名为 vite.config.js 的配置文件,该文件位于 项目根目录 中(也支持其他 JS 和 TS 扩展名)。
最基本的配置文件如下所示
// vite.config.js
export default {
// config options
}请注意,即使项目没有使用原生 Node ESM(例如 package.json 中的 type: "module"),Vite 也支持在配置文件中使用 ES 模块语法。在这种情况下,配置文件会在加载前自动预处理。
您还可以使用 --config CLI 选项显式指定要使用的配置文件(相对于 cwd 解析)
vite --config my-config.js配置 Intellisense
由于 Vite 附带 TypeScript 类型定义,因此您可以利用 IDE 的 Intellisense 和 jsdoc 类型提示。
/** @type {import('vite').UserConfig} */
export default {
// ...
}或者,您可以使用 defineConfig 辅助函数,该函数应该可以提供 Intellisense,而无需 jsdoc 注解。
import { defineConfig } from 'vite'
export default defineConfig({
// ...
})Vite 也支持 TypeScript 配置文件。您可以使用 vite.config.ts 和上面的 defineConfig 辅助函数,或者使用 satisfies 运算符。
import type { UserConfig } from 'vite'
export default {
// ...
} satisfies UserConfig条件配置
如果配置需要根据命令(serve 或 build)、使用的 模式、是否为 SSR 构建(isSsrBuild)或是否正在预览构建(isPreview)有条件地确定选项,则可以导出一个函数。
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
if (command === 'serve') {
return {
// dev specific config
}
} else {
// command === 'build'
return {
// build specific config
}
}
})需要注意的是,在 Vite 的 API 中,command 值在开发期间为 serve(在 cli 中 vite、vite dev 和 vite serve 是别名),在构建生产环境时为 build (vite build)。
isSsrBuild 和 isPreview 是额外的可选标志,用于区分 build 和 serve 命令的类型。一些加载 Vite 配置的工具可能不支持这些标志,并将传递 undefined。因此,建议使用与 true 和 false 的显式比较。
异步配置
如果配置需要调用异步函数,则可以导出一个异步函数。并且此异步函数也可以通过 defineConfig 传递,以获得更好的 Intellisense 支持。
export default defineConfig(async ({ command, mode }) => {
const data = await asyncFunction()
return {
// vite config
}
})在配置中使用环境变量
环境变量可以像往常一样从 process.env 中获取。
请注意,Vite 默认不加载 .env 文件,因为要加载的文件只能在评估 Vite 配置后才能确定,例如,root 和 envDir 选项会影响加载行为。但是,如果需要,您可以使用导出的 loadEnv 辅助函数加载特定的 .env 文件。
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
// Load env file based on `mode` in the current working directory.
// Set the third parameter to '' to load all env regardless of the
// `VITE_` prefix.
const env = loadEnv(mode, process.cwd(), '')
return {
// vite config
define: {
__APP_ENV__: JSON.stringify(env.APP_ENV),
},
}
})