Webtorrent v2.1.27能否在Node.js(TypeScript)环境运行?配置报错求助
解决TypeScript Express项目中Webtorrent的ESM兼容错误
在TypeScript编写的Express应用中使用Webtorrent包时,无论如何配置tsconfig.json,始终出现以下编译错误:
Error [ERR_REQUIRE_ESM]: require() of ES Module C...\node_modules\webtorrent\index.js from ...src\controllers\TorrentParser.ts not supported. index.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in ...\node_modules\webtorrent\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
当前使用的tsconfig.json配置如下:
{ "compilerOptions": { "esModuleInterop": true, "skipLibCheck": true, "target": "es2022", "allowJs": true, "resolveJsonModule": true, "moduleDetection": "force", "strict": true, "noImplicitAny": true, "noUncheckedIndexedAccess": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "NodeNext", "module": "NodeNext", "outDir": "./dist", "rootDir": "./src", "types": ["node", "express", "webtorrent"], "allowSyntheticDefaultImports": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"], "ts-node": { "files": true } }
可行解决方案
方案1:使用动态import()加载Webtorrent
Webtorrent是ESM模块,若项目输出为CommonJS,可将静态导入改为动态导入:
// 替换原静态导入语句 const WebTorrent = (await import('webtorrent')).default;
注意:该代码需放在async函数内执行,或通过.then()处理异步逻辑。
方案2:将项目切换为ESM模式
- 修改项目根目录的
package.json,添加"type": "module" - 调整tsconfig.json的编译选项:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "target": "ES2022", // 其余配置保持不变 }, // 其余配置不变 }
切换为ESM模式后,所有文件导入需使用完整扩展名(如.ts、.js)。
方案3:使用CommonJS兼容方式(不推荐)
不建议直接修改node_modules/webtorrent/package.json中的"type": "module"为"commonjs",这种方式维护性差,可能引发版本兼容问题。若前两种方案无法使用,可尝试使用esm等工具做模块桥接,但优先推荐前两种方案。
内容的提问来源于stack exchange,提问作者PiwiTheKiwi
相关产品推荐
相关产品推荐

