这其实是Astro v6的一个改动,Changed: import.meta.env values are always inlined:
In Astro 5.13, the experimental.staticImportMetaEnv flag was introduced to update the behavior when accessing import.meta.env directly to align with Vite’s handling of environment variables and ensures that import.meta.env values are always inlined.
In Astro 5.x, non-public environment variables were replaced by a reference to process.env. Additionally, Astro could also convert the value type of your environment variables used through import.meta.env, which could prevent access to some values such as the strings “true” (which was converted to a boolean value), and “1” (which was converted to a number).
Astro 6 removes this experimental flag and makes this the new default behavior in Astro: import.meta.env values are always inlined and never coerced.
所以下面这篇文章讨论的前提,都是Astro v6。
Astro官方文档里有关于环境变量的章节,Using environment variables,里面有个例子:
1 | // When import.meta.env.SSR === true |
它主要使用Vite的环境变量,Env Variables and Modes,但这里其实就有个坑点,那就是这种方式的值会在build的时候被替换成实际的值,而不是在运行时动态获取,这意味着:
- 在build的时候就需要提供这个环境变量,不然无法替换;
- 在运行时无法改变这个变量,因为他已经被写入了构造物里。
假设你在代码里写了:
1 | const db = drizzle(import.meta.env.DATABASE_URL); |
那么在build时提供了系统环境变量或者.env的时候,且值是 mysql://user:password@localhost:3306/db,它最终的dist会变成(也就是直接inline替换了):
1 | const db = drizzle("mysql://user:password@localhost:3306/db"); |
