gpt4 book ai didi

javascript - Vite:在构建时替换环境变量

转载 作者:行者123 更新时间:2023-12-05 00:33:23 29 4
gpt4 key购买 nike

我正在使用 Vue + Vite + TS,并且正在构建一些我想在其他地方构建和导入的库。
关键是我使用 dotenv 设置了一些环境变量,因此我可以使用 import.meta.env.MY_VARIABLE 之类的东西。
但是它们在我运行它们的地方的运行时被使用,因此需要将 env 文件放在需要这些库的组件中。
我想知道是否有办法让它们在构建时被替换。

最佳答案

也许您想使用 定义 选项。

let commonConfig =
{

plugins: [vue()],

resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url))
},
},
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
nested: resolve(__dirname, 'auth_redirect.html')
}
}
}
}

export default defineConfig(({ command, mode, ssrBuild }) => {

if (command === 'serve')
{
//
return commonConfig;

}
else
{
commonConfig.define = {
"BUILD_TIMESTAMP": new Date().toISOString()

};

// command === 'build'
return commonConfig;
}
})
然后您可以将 BUILD_TIMESTAMP 分配给您的 appCode 中的任何 javascript 变量。 const buildNum = "BUILD_TIMESTAMP";//You will get right val in this .
定义必须与 https://esbuild.github.io/api/#non-analyzable-imports 兼容所以在服务模式下会出现问题。所以我只在构建模式下有条件地使用它。
在开发模式下,您只会看到 buildNum 变量的原始值。

关于javascript - Vite:在构建时替换环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71082688/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com