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

创建NPM库时Webpack导入目录模块报错:无法解析'./endpoints'

解决Webpack "Module not found: Can't resolve './endpoints'" 错误

你的问题核心在于模块导入逻辑和Webpack的默认解析规则不匹配,结合你的文件结构与配置,我整理了几个针对性的解决方案:

方案1:给endpoints目录添加index.js入口文件

当你在src/index.js里写import {endpoint1} from './endpoints'时,Webpack会默认去endpoints目录下查找index.js文件(这是Node.js和Webpack通用的模块解析规则),但你目前的endpoints目录只有endpoint1.js,所以会报错。

只需在src/endpoints下创建一个index.js,统一导出目录内的模块:

// src/endpoints/index.js
export { endpoint1 } from './endpoint1';

这样原来的导入语句就能正常工作,Webpack会自动识别这个目录入口文件。

方案2:直接导入具体模块文件

如果不想额外创建index.js,可以修改src/index.js里的导入路径,直接指向endpoint1.js:

// src/index.js
import { endpoint1 } from './endpoints/endpoint1';
module.exports = class lib { ... }

这种方式更直接,适合模块数量较少的场景。

方案3:调整Webpack的resolve配置(可选优化)

你当前的resolve.modules配置把src/endpoints加入了模块搜索路径,但这个配置是针对非相对路径的模块导入(比如import 'endpoint1'),对你的相对路径导入./endpoints完全不起作用,反而可能造成解析混淆。

如果想简化后续的模块导入,可以改用alias配置:

// webpack.config.js
const path = require('path');
module.exports = {
  // ...其他原有配置
  resolve: {
    extensions: ['.js'],
    alias: {
      '@endpoints': path.resolve(__dirname, 'src/endpoints')
    }
  }
};

之后你就可以用更简洁的路径导入模块:

import { endpoint1 } from '@endpoints/endpoint1';

额外提示:清理无效的resolve配置

建议移除你当前resolve.modules里的path.resolve(__dirname, 'src/endpoints'),改成更通用的配置,避免干扰正常的相对路径解析:

resolve: {
  modules: [path.resolve(__dirname, 'src'), 'node_modules'],
  extensions: ['.js']
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:33:30