__dirname is not defined in ES module scope
Updated:
__dirname Is not Defined in ES Module Scope
在 package.json 中的 type = module 的项目中,我创建了一个 ts 文件,类型是 esm 的类型。
这里的报错是因为我们错误的使用了 module 的语法到 esm 的文件中,要解决这个问题的方法有两种,第一种改为 module,另一种是改为 esm 的写法。
首先是第一种改为 module 的写法,那就是把 import 改为 require,然后由于我们这里是 module 的项目,所以需要修改一下 ts 文件的后缀 ts 改为 cts。
一个供参考的例子:GitHub - shawnsparks/typescript-esm: Explore different usage patterns of ES modules with Typescript
然后是第二种,文件、路径相关的改为 esm 的写法。
import { fileURLToPath } from "url"import path from "path"
// 获取当前模块的目录路径const __filename = fileURLToPath(import.meta.url)const __dirname = path.dirname(__filename)
感谢阅读到这里,期待收到更多的反馈
欢迎关注公众号
kazoottt
