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

如何在单个TypeScript文件中兼容CommonJS与ESModule获取当前文件目录路径?

在单个TypeScript文件中兼容CommonJS与ESModule的当前目录路径获取方案

在不同模块规范下,获取当前文件目录路径的原生写法存在差异:

  • CommonJS环境可直接使用__dirname:
const dir = __dirname;
  • ESModule环境则依赖import.meta.url:
const dir = import.meta.url;

但import.meta属于ESModule专属语法,在CommonJS环境中会触发语法错误,直接编写条件分支无法规避该问题。以下是我尝试过的两种方案及遇到的问题:

尝试方案一

const dir = typeof require === "function" ? __dirname : import.meta.dirname;

CommonJS环境报错:SyntaxError: Cannot use 'import.meta' outside a module。原因是CommonJS会对整个文件做语法解析,即便import.meta处于条件分支中,也会被判定为非法语法。

尝试方案二

const dir = typeof require === "function"
   ? new Function("return __dirname;")()
   : new Function("return import.meta.dirname;")();

ESModule环境报错:SyntaxError: Cannot use 'import.meta' outside a module。推测是new Function执行时的上下文仍会对import.meta做语法校验,导致报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:18:10