import.meta.env的打字稿类型

我现在正在使用一个框架 (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;
    }
  }
}

我尝试了以下但不起作用。

declare global {
  namespace NodeJS {
    interface ImportMeta {
      GITHUB_AUTH_TOKEN: string;
      NODE_ENV: 'development' | 'production';
      PORT?: string;
      PWD: string;
    }
  }
}

回答

它记录在这里: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;
  };
}

但请注意,在 vite 中,所有环境变量都必须以前缀为前缀,VITE_因此这些环境变量在应用程序中均不可用。


以上是import.meta.env的打字稿类型的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>