配置 Vite
从命令行运行 vite
时,Vite 会自动尝试解析 项目根目录下的名为 vite.config.js
的配置文件(也支持其他 JS 和 TS 扩展名)。
最基本的配置文件如下所示
export default {
// config options
}
请注意,即使项目未使用原生 Node ESM(例如 package.json
中的 "type": "module"
),Vite 也支持在配置文件中使用 ES 模块语法。 在这种情况下,配置文件会在加载前自动进行预处理。
您还可以使用 --config
CLI 选项显式指定要使用的配置文件(相对于 cwd
解析)
vite --config my-config.js
配置加载
默认情况下,Vite 使用 esbuild
将配置打包成临时文件并加载它。 当在 monorepo 中导入 TypeScript 文件时,这可能会导致问题。 如果您遇到此方法的任何问题,则可以指定 --configLoader runner
以改用 模块运行器,它不会创建临时配置,并将动态转换任何文件。 请注意,模块运行器不支持配置文件中的 CJS,但外部 CJS 包应像往常一样工作。
或者,如果您使用的环境支持 TypeScript(例如 node --experimental-strip-types
),或者如果您仅编写纯 JavaScript,则可以指定 --configLoader native
以使用环境的本机运行时来加载配置文件。 请注意,不会检测到配置文件导入的模块的更新,因此不会自动重启 Vite 服务器。
配置智能提示
由于 Vite 附带 TypeScript 类型定义,因此您可以利用 IDE 的智能提示和 jsdoc 类型提示
/** @type {import('vite').UserConfig} */
export default {
// ...
}
或者,您可以使用 defineConfig
助手,它应该提供智能提示,而无需 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
传递,以获得改进的智能提示支持
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),
},
}
})
在 VS Code 上调试配置文件
使用默认的 --configLoader bundle
行为时,Vite 会将生成的临时配置文件写入 node_modules/.vite-temp
文件夹,并且在 Vite 配置文件中设置断点调试时会发生文件未找到错误。 要解决此问题,请将以下配置添加到 .vscode/settings.json
{
"debug.javascript.terminalOptions": {
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**",
"**/node_modules/.vite-temp/**"
]
}
}