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

Node.js TypeScript中Dotenv配置问题及模块找不到错误求助

Node.js + TypeScript + env配置问题排查

问题情况

配置环境变量时遇到异常,执行指定命令后提示找不到目标模块,相关配置及错误信息如下:

package.json配置

{
  ...
  "type": "module",
  "scripts": {
    "dev": "nodemon"
  },
  "dependencies": {
    "@supabase/supabase-js": "^2.45.6",
    "body-parser": "^1.20.3",
    "dotenv": "^16.4.5",
    "express": "^4.21.1"
  },
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "^22.7.9",
    "nodemon": "^3.1.7",
    "ts-node": "^10.9.2",
    "typescript": "^5.6.3"
  }
}

tsconfig.json配置

{
  "compilerOptions": {
    "target": "es2016",
    "lib": ["es6"],
    "module": "ESNext",
    "rootDir": "/",
    "moduleResolution": "node10",
    "resolveJsonModule": true,
    "allowJs": true,
    "outDir": "build",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true
  }
}

版本信息

  • nodejs: 21.6.1

执行命令与错误

执行命令:

node --env-file=.env ./ĩndex.ts

错误信息:

Error: Cannot find module '/backend/ĩndex.ts'

解决建议

1. 核对文件名与路径

  • 检查命令中的ĩndex.ts是否存在拼写错误:注意文件名里的i带特殊波浪线,确认实际文件名是否一致,建议改为标准的index.ts避免特殊字符引发识别问题。
  • 执行pwd(Linux/macOS)或echo %cd%(Windows)确认当前工作目录,确保目标文件确实存在于当前路径下,或直接使用绝对路径指定文件位置。

2. 修正TypeScript执行方式

Node.js无法直接运行.ts文件,需通过ts-node执行,修正后命令:

ts-node --env-file=.env ./index.ts

同时建议修改package.json的dev脚本,让nodemon正确处理TypeScript文件:

"scripts": {
  "dev": "nodemon --exec ts-node index.ts"
}

3. 调整tsconfig配置

  • rootDir设为"/"会覆盖全局目录,建议改为实际源码目录(比如"./src"),缩小编译范围:
    "rootDir": "./src"
    
  • moduleResolution设为node10与module: ESNext存在兼容性冲突,建议改为node或bundler:
    "moduleResolution": "node"
    

4. 确保环境变量加载

如果使用ts-node,除了--env-file参数,也可在入口文件顶部添加dotenv加载逻辑,保障环境变量正常读取:

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:02:42