cpp*_*ner 7 typescript vue.js vite
我现在正在使用一个框架 (vite) 将环境变量注入import.meta.env.
我以前能够创建一个文件env.d.ts来提供类型process.env
declare global {
namespace NodeJS {
interface ProcessEnv {
GITHUB_AUTH_TOKEN: string;
NODE_ENV: 'development' | 'production';
PORT?: string;
PWD: string;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下但不起作用。
declare global {
namespace NodeJS {
interface ImportMeta {
GITHUB_AUTH_TOKEN: string;
NODE_ENV: 'development' | 'production';
PORT?: string;
PWD: string;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Nor*_*ldt 146
我有类似的问题并解决了
tsconfig.json
{
...
"compilerOptions": {
...
"target": "ESNext",
"types": ["vite/client"]
}
}
Run Code Online (Sandbox Code Playgroud)
已vite作为开发依赖项安装。
cpp*_*ner 15
我通过使用以下内容让它工作 -
interface ImportMetaEnv {
VITE_PORT?: string;
VITE_AUTH_TOKEN?: string;
}
Run Code Online (Sandbox Code Playgroud)
lou*_*ton 10
根据此处的文档https://vitejs.dev/guide/env-and-mode.html#intellisense您可以执行以下操作:
// env.d.ts
interface ImportMetaEnv extends Readonly<Record<string, string>> {
readonly VITE_APP_TITLE: string
// more env variables...
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
Run Code Online (Sandbox Code Playgroud)
上面答案中链接到的此文档的 URL已更新。
此外,env.d.ts应放置在您的src/目录中,并且您需要在文件顶部有一个参考字符串。
一个完整的工作示例如下:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_CUSTOM_ENV_VARIABLE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
Run Code Online (Sandbox Code Playgroud)
VITE_如果您不想使用默认变量前缀,您可以在 Vite 配置中更改它:
{
envPrefix: 'YOURPREFIX_',
}
Run Code Online (Sandbox Code Playgroud)
它记录在这里:https : //www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#support-for-importmeta
所以你快到了:
interface ImportMeta {
env: {
GITHUB_AUTH_TOKEN: string;
NODE_ENV: 'development' | 'production';
PORT?: string;
PWD: string;
};
}
Run Code Online (Sandbox Code Playgroud)
但请注意,在 vite 中,所有环境变量都必须以前缀为前缀,VITE_因此这些环境变量在应用程序中均不可用。
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |