外部包中require无法加载指定路径文件的技术求助
问题描述
我正在开发一款插件管理器,功能涵盖PostgreSQL数据库迁移、CRUD前端生成及CRUD GraphQL mutation生成,计划做成可配合Next.js使用的外部包,实现独立更新且不影响主项目。该功能原本在主项目内已接近完成,后被提取为外部包。
目前遇到的问题:用fs.readdir读取./src/plugins目录正常,但执行require(./src/plugins/${file}/index.ts)时触发模块找不到错误,错误信息如下:
Error: Cannot find module './src/plugins/example/index.ts' Require stack: - E:\nextpower\lib\cjs\commands.js at Module._resolveFilename (node:internal/modules/cjs/loader:995:15) at Module._load (node:internal/modules/cjs/loader:841:27) at Module.require (node:internal/modules/cjs/loader:1061:19) at require (node:internal/modules/cjs/helpers:103:18) at E:\nextpower\lib\cjs\commands.js:39:34 at Generator.next (<anonymous>) at fulfilled (E:\nextpower\lib\cjs\commands.js:7:58) { code: 'MODULE_NOT_FOUND', requireStack: [ 'E:\\nextpower\\lib\\cjs\\commands.js' ]
解决思路
1. 修正路径基准
错误栈显示代码从E:\nextpower\lib\cjs\commands.js执行,你用的相对路径./src/plugins是相对于当前执行文件的目录,而非源码目录,打包后的lib/cjs目录下不存在src文件夹,导致找不到模块。
解决代码示例:
const path = require('path'); // 基于当前文件目录生成绝对路径 const pluginAbsolutePath = path.resolve(__dirname, '../../src/plugins', file, 'index.ts'); const plugin = require(pluginAbsolutePath);
同时需确保打包工具(如tsup、rollup)将src/plugins目录下的文件复制到输出目录,可在tsconfig.json的include字段添加src/plugins。
2. 处理TypeScript文件加载问题
Node.js的CommonJS loader无法直接加载.ts文件,若直接require源码中的.ts文件会触发错误。
解决方法:
- 确保插件文件已编译为
.js,然后require对应的.js路径; - 生产环境避免依赖
ts-node这类实时编译工具,改用动态import()配合TypeScript配置,确保打包时正确处理模块导入。
3. 调整打包工具配置
如果使用tsup、rollup等工具,可能未将src/plugins纳入打包范围,导致输出包中缺少插件文件。
解决示例(tsup配置):
export default defineConfig({ entry: ['src/index.ts', 'src/plugins/**/*'], // 其他打包配置... });
内容的提问来源于stack exchange,提问作者Alexandre Bove
相关产品推荐
相关产品推荐

