![](/img/trans.png)
[英]process.env doesn't contain ENV VARS when `npm run build` (Ubuntu)
[英]Vite: Replace env vars at build time
我正在使用 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 变量的原始值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.