Configuration

环境变量

编辑此页面

Solid 建立在 Vite 之上,它提供了一种处理环境变量的便捷方法。


公共环境变量

公共变量被认为可以安全地暴露给客户端代码。这些变量以 VITE_ 为前缀,并在编译时注入到客户端代码中。

在项目的根目录中,创建一个名为 .env 的文件。该文件将以 key = value 格式存储环境变量。

如果使用 TypeScript,通过在项目的根目录中创建一个名为 .env.d.ts 的文件,可以使此类变量类型安全,并使 TypeScript 语言服务提供程序 (LSP) 进行自动补全。

interface ImportMetaEnv {
readonly VITE_USER_ID: string;
readonly VITE_PUBLIC_ENDPOINT: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
function MyComponent() {
return (
<div>
<h2>
Component with environment variable used{" "}
{import.meta.env.VITE_VARIABLE_NAME}
the value will be replaced during compilation time.
</h2>
</div>
);
}

私有环境变量

这些变量只能在后端代码中访问,因此最好不要使用 VITE_ 前缀。相反,请使用 process.env 来访问它们。根据所选的 Nitro 预设,它们将自动可用,或者需要外部依赖项,例如 dotenv

DB_HOST="somedb://192.110.0"
DB_PASSWORD = super_secret_password_hash

要访问它们,请在后端代码中使用 process.env。例如,请查看下面的伪代码。

"use server"
const client = new DB({
host: process.env.DB_URL,
password: process.env.DB_PASSWORD
});

还可以通过相同的 .env.d.ts 文件使 process.env 类型安全。

declare namespace NodeJS {
interface ProcessEnv {
readonly DB_URL: string
readonly DB_PASSWORD: string
}
}
报告此页面问题