查看文档发现Vite 环境变量是通过import.meta.env 对象暴露的,但在vite.config中行不通,经过一通乱找,发现原来是这样用的:
const envResolve = (mode: string, env: string) => loadEnv(mode, process.cwd())[env];
export default ({ command, mode }: ConfigEnv): UserConfigExport =>{
return {
base: envResolve(mode, 'VITE_PUBLIC'),
plugins: [vue()]
}
}
具体原因:
There’s a chicken-egg problem here: Vite expects to resolve .env files from project root, but project root can be made different by the config file.
So if we resolve .env before resolving the config file, we can only resolve it from CWD, which would then break the case where the user puts .env files in a nested root specified via config.
——Evan You
博客探讨了在Vite中如何正确处理环境变量的问题。由于Vite的配置文件加载顺序导致的先验环境变量解析问题,作者提供了一个解决方案:使用envResolve函数动态加载.env文件。该函数确保了即使.env文件位于配置文件指定的不同根目录下,也能正常工作。博客还引用了Vite创建者Evan You的解释,强调了配置文件与.env文件解析的正确顺序对于避免冲突的重要性。
8309

被折叠的 条评论
为什么被折叠?



