You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript项目中.env文件变量访问失败求助

问题梳理与解决方案方向

环境与项目基础信息

  • 开发环境:React TypeScript、Dotenv、MacAir M2
  • 依赖安装指令:cd smart-contract; yarn; yarn compile; cd ../minting-dapp; yarn; yarn build
  • DApp启动指令:cd minting-dapp && yarn dev-server

项目目录结构

主项目根目录
├── minting-dapp(Folder1)
│   ├── node_modules
│   ├── public
│   └── src
│       └── scripts
│           └── react
│               └── dapp.tsx  # 自定义代码位置
└── smart-contract(Folder2)
    ├── node_modules
    ├── scripts
    │   └── reveal.tsx
    ├── hardhat.config
    └── .env  # 环境变量文件位置

smart-contract下的.env内容

COLLECTION_URI_PREFIX=something
BLOCK_EXPLORER_API_KEY=something
ALCHEMY_GEORLI_API_KEY=somethin
ALCHEMY_MAINNET_API_KEY=something

尝试的三种方法及问题

方法1:跨目录导入smart-contract下的dotenv

在dapp.tsx中编写代码:

import * as dotenv from '../../../../smart-contract/node_modules/dotenv';
dotenv.config();
// 测试输出
console.log(process.env.ALCHEMY_GEORLI_API_KEY);

报错信息:

Module build failed: Module not found: "./node_modules/dotenv/lib/main.js" contains a reference to the file "fs". This file can not be found, please check it for typos or update it if the file got moved.

方法2:复用hardhat.config.ts的导入方式

未在minting-dapp目录安装dotenv,直接写:

import * as dotenv from 'dotenv';
dotenv.config();

报错信息:

Cannot find module 'dotenv'

方法3:复用reveal.tsx的直接调用方式

直接在dapp.tsx中调用:

console.log(process.env.ALCHEMY_GEORLI_API_KEY);

结果:输出undefined

注:dotenv仅在smart-contract目录下安装

关键修正与方案方向

已明确前端代码直接访问API密钥会导致密钥公开泄露,完全违背.env文件保护敏感信息的初衷。正确的做法是通过服务器端封装逻辑,由后端读取环境变量并处理相关请求,前端仅与后端接口交互,避免直接接触敏感密钥。

内容的提问来源于stack exchange,提问作者esra45500

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:42:51