首页 > 解决方案 > 库使用 __dirname 导致模块中的错误

问题描述

所以我有一个type设置为modulein的打字稿应用程序package.json

到目前为止,一切都很好,但是现在在我导入了谷歌语音 api 之后,在尝试运行应用程序时一切都中断了。

> node build --prod

file:///opt/jap/server/build/index.js:132416
    var googleProtoFilesDir = path.join(__dirname, "..", "..", "protos");
                                        ^

ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/opt/jap/server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

我想有点道理,但我无法更改应用程序的类型,而且.js文件不是我可以控制的,因为它是依赖项。

我试过在没有运气的情况下添加,我已经添加"types": ["node"]为依赖项,也没有任何成功。compilerOptionstsconfig.json"@types/node": "^16.9.1"

那么有什么明显的解决方案吗?

"esModuleInterop": true还有:我确实有tsconfig.json

标签: javascriptnode.jstypescript

解决方案


推荐阅读