Loading

Jenkins构建时SWR模块导入报错解决方案

问题描述

在本地环境打包正常,但在Jenkins环境构建时遇到了与SWR库相关的模块导入错误。错误信息显示无法从非ECMAScript模块中导入命名导出,只能使用默认导出。主要报错如下:

Can't import the named export 'createContext' from non EcmaScript module (only default export is available)
Can't import the named export 'createElement' from non EcmaScript module (only default export is available)
Can't import the named export 'useCallback' from non EcmaScript module (only default export is available)
// ... 更多类似错误

问题原因

这个问题主要是由于:

  • SWR 2.x版本使用了纯ESM模块规范
  • 项目的webpack配置与新版本SWR的ESM模块系统不兼容
  • Jenkins环境与本地开发环境的构建配置差异

解决方案

1. 降级SWR版本

将SWR版本降级到1.3.0版本,这个版本使用了更兼容的模块系统。在package.json中添加:

{
  "dependencies": {
    "swr": "1.3.0"
  }
}

2. 添加版本锁定

为了确保所有依赖包使用相同版本的SWR,在package.json中添加resolutions配置:

{
  "resolutions": {
    "swr": "1.3.0"
  }
}

3. 重新安装依赖

完成配置修改后,需要:

  • 删除node_modules文件夹
  • 删除package-lock.json或yarn.lock文件
  • 重新运行npm install或yarn install
  • 重新构建项目

其他注意事项

如果问题仍然存在,可以检查:1. Jenkins环境中的Node.js版本是否与本地开发环境一致

  • 确保Jenkins使用的npm/yarn版本与本地开发环境一致
  • 如果使用yarn,可以在Jenkins构建脚本中使用yarn install --force

总结

这个问题主要是由于模块系统的兼容性导致的,通过降级SWR版本并确保依赖版本一致性可以解决。这个案例也提醒我们在使用新版本库时要注意模块系统的兼容性问题,特别是在不同环境下的构建过程中。

 

posted @ 2025-02-20 11:45  冯叶青  阅读(122)  评论(0)    收藏  举报