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

如何在TypeScript的tsx REPL中正确使用dotenv?

问题描述

运行npx tsx进入REPL环境后,尝试引入dotenv并加载配置:

> const dotenv = require('dotenv');
> dotenv.config({ path: './config/env' }); // 该目录下有index.ts文件

执行后出现目录读取错误:

{
  error: Error: EISDIR: illegal operation on a directory, read
      at Object.readSync (node:fs:749:3)
      at tryReadSync (node:fs:449:20)
      at Object.readFileSync (node:fs:495:19)
      at Object.configDotenv (/server/node_modules/dotenv/lib/main.js:198:42)
      at Object.config (server/node_modules/dotenv/lib/main.js:223:25)
      at REPL2:1:8
      at Script.runInThisContext (node:vm:129:12)
      at REPLServer.defaultEval (node:repl:572:29)
      at bound (node:domain:433:15)
      at REPLServer.runBound (node:domain:444:12) {
    errno: -21,
    syscall: 'read',
    code: 'EISDIR'
  }
}

改为指定具体TS文件路径后:

> dotenv.config({ path: './config/env/index.ts' });

得到的结果不符合预期,配置中的计算属性未被执行,仅保留原始字符串:

{
 parsed: {
    root: "path.join(path.dirname('.'), '/..'),",
    api: '{',
    title: "'API: Users and Application Resources',",
    version: "'0.0.1',",
    description: "'A RESTful API for managing users and application resources.',",
    fileSizeLimit: '10 * 1024 * 1024,'
  }
}

询问能否在tsx REPL中使用dotenv创建正确的配置。

解决方案
  • dotenv的核心限制:dotenv仅用于解析.env格式的纯文本环境变量文件,不支持执行TS/JS代码逻辑。直接传入TS文件路径时,它会把文件内容当作普通文本逐行解析,自然无法处理代码中的计算逻辑。

  • 可行的替代方案:

    1. REPL中手动编写配置逻辑:直接在REPL里执行配置的计算代码,生成所需配置对象:
      > const path = require('path');
      > const config = {
          root: path.join(path.dirname('.'), '/..'),
          api: {
            title: 'API: Users and Application Resources',
            version: '0.0.1',
            description: 'A RESTful API for managing users and application resources.',
          },
          fileSizeLimit: 10 * 1024 * 1024
        };
      
    2. 导入预定义的配置模块:将配置逻辑封装成可导出的TS模块,在REPL中直接导入使用:
      • 确保./config/env/index.ts为导出配置的模块:
        import path from 'path';
        
        export default {
          root: path.join(path.dirname('.'), '/..'),
          api: {
            title: 'API: Users and Application Resources',
            version: '0.0.1',
            description: 'A RESTful API for managing users and application resources.',
          },
          fileSizeLimit: 10 * 1024 * 1024
        };
        
      • 在REPL中导入:
        > import config from './config/env/index.ts';
        
    3. 静态化配置到.env文件(仅适合静态值):如果必须使用dotenv,可以先在代码中计算出配置值,写入.env文件后再用dotenv加载,但这种方式无法支持动态计算的配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:53:15