TypeScript中使用process.env作为对象值时无法访问属性的问题
解决TypeScript中process.env访问报错的问题
首先看你代码里的致命错误:把process拼写成了prcoess,这就是报错“Cannot find namespace 'prcoess'”的直接原因,先把拼写改过来:
const MAIL_SETTINGS = { service: 'gmail', auth: { user: process.env.MAIL_EMAIL, pass: process.env.MAIL_PASSWORD, }, };
如果改完拼写后还是有process不存在的报错,按以下步骤处理:
安装Node.js类型定义包,TypeScript需要它来识别Node.js全局变量:
npm install @types/node --save-dev # 或者用yarn yarn add @types/node --dev检查
tsconfig.json的compilerOptions,确保包含node类型:{ "compilerOptions": { "types": ["node"] } }如果是前端项目(比如React、Vue),还需要添加环境变量的类型声明,新建
env.d.ts文件:declare global { namespace NodeJS { interface ProcessEnv { MAIL_EMAIL: string; MAIL_PASSWORD: string; } } } export {};这样TypeScript会识别你的自定义环境变量,避免类型提示错误。
另外要确保环境变量已经正确加载:如果用了dotenv管理环境变量,要在项目入口文件最顶部加载它:
// CommonJS require('dotenv').config(); // ES模块 import 'dotenv/config';
内容的提问来源于stack exchange,提问作者Brahm Bind Singh
相关产品推荐
相关产品推荐

