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

升级Webpack 5后启动项目出现模块解析错误求助

解决date-fns/add_hours模块解析失败问题

问题详情

运行项目时出现23条同类模块解析错误,示例错误信息如下:

ERROR in ./node_modules/@remotelock/react-week-scheduler/index.mjs
5:0-42 Module not found: Error: Can't resolve 'date-fns/add_hours' in
'C:\Users\platform2-frontend\node_modules@remotelock\react-week-scheduler'
Did you mean 'index.js'? BREAKING CHANGE: The request
'date-fns/add_hours' failed to resolve only because it was resolved as
fully specified (probably because the origin is strict EcmaScript
Module, e. g. a module with javascript mimetype, a '.mjs' file, or a
'.js' file where the package.json contains '"type": "module"').

The extension in the request is mandatory for it to be fully
specified. Add the extension to the request.

已尝试的操作:

  • 将date-fns、@remotelock/react-week-scheduler更新至最新版本
  • 修改项目内date-fns导入方式为import { format } from 'date-fns'
  • 升级React从16.14到18版本

可行解决方案

1. 修复第三方包的导入路径(持久化修改)

错误核心是react-week-scheduler的.mjs文件属于严格ES模块,导入date-fns子模块时未指定文件扩展名,导致解析失败。

直接修改node_modules/@remotelock/react-week-scheduler/index.mjs里的所有相关导入:
把import addHours from 'date-fns/add_hours'这类语句,改为import addHours from 'date-fns/add_hours/index.js'(根据date-fns实际文件结构调整扩展名,比如.mjs)。

为避免重新安装依赖后修改失效,用patch-package持久化补丁:

  • 安装依赖:npm install patch-package --save-dev
  • 修改完文件后执行:npx patch-package @remotelock/react-week-scheduler
  • 提交生成的patches文件夹到版本控制,后续npm install会自动应用补丁

2. 配置webpack扩展解析规则

如果不想修改第三方包,可在webpack配置中添加无扩展名模块的解析支持:
在webpack.config.js的resolve部分添加:

module.exports = {
  resolve: {
    extensions: ['.mjs', '.js', '.jsx', '.json'],
    extensionAlias: {
      '.js': ['.js', '.mjs'],
    }
  }
}

如果是CRA项目,用craco修改配置:

  • 安装craco:npm install @craco/craco --save-dev
  • 创建craco.config.js:
module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      webpackConfig.resolve.extensions.push('.mjs');
      webpackConfig.resolve.extensionAlias = {
        '.js': ['.js', '.mjs'],
      };
      return webpackConfig;
    }
  }
}

修改package.json的启动脚本为craco start、craco build、craco test

3. 降级date-fns到兼容版本

新版本date-fns的模块结构可能和react-week-scheduler的导入逻辑不兼容,试试降级到2.29.3这个稳定版:

npm install date-fns@2.29.3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:45:52