Skip to content

环境变量 API 参考

Added in: astro@5.0.0

astro:env API 允许你为已设置的环境变量配置类型安全模式。这允许你指示它们是否应该在服务器或客户端上可用,并定义它们的数据类型和附加属性。有关示例和使用说明,请参阅 参见 astro:env 指南

¥The astro:env API lets you configure a type-safe schema for environment variables you have set. This allows you to indicate whether they should be available on the server or the client, and define their data type and additional properties. For examples and usage instructions, see the astro:env guide.

¥Imports from astro:env

import {
getSecret,
} from 'astro:env';

Added in: astro@5.0.0

getSecret() 助手函数允许通过其键检索环境变量的原始值。

¥The getSecret() helper function allows retrieving the raw value of an environment variable by its key.

例如,你可以将布尔值检索为字符串:

¥For example, you can retrieve a boolean value as a string:

import {
FEATURE_FLAG, // boolean
getSecret
} from 'astro:env/server'
getSecret('FEATURE_FLAG') // string | undefined

这对于获取未在你的架构中定义的机密也很有用,例如依赖于来自数据库或 API 的动态数据的机密。

¥This can also be useful to get a secret not defined in your schema, for example one that depends on dynamic data from a database or API.

如果你需要以编程方式检索环境变量,我们建议使用 getSecret() 而不是 process.env(或等效项)。因为它的实现是由你的适配器提供的,所以如果你切换适配器,则无需更新所有调用。在开发和构建中,它默认为 process.env

¥If you need to retrieve environment variables programmatically, we recommend using getSecret() instead of process.env (or equivalent). Because its implementation is provided by your adapter, you won’t need to update all your calls if you switch adapters. It defaults to process.env in dev and build.

Astro 中文网 - 粤ICP备13048890号