Nx Monorepo+Next.js中使用Swiper.js的ES模块问题求助
问题
在Nx Monorepo + Next.js项目中使用Swiper.js时遇到ES模块兼容问题。Swiper更新为ES模块后,引入该库的页面触发以下错误:
Error: require() of ES Module lalala… swiper/modules/index.mjs not supported. Instead change the require of lalala… /swiper/modules/index.mjs to a dynamic import() which is available in all CommonJS modules.
临时方案是在导入前加感叹号排除转译:
import { Swiper, SwiperSlide } from '!swiper/react'
但该方案需要Mock组件才能测试,并非理想解。尝试在webpack配置中排除Swiper转译未成功,推测是项目结构复杂导致操作有误。
复现条件:仅使用自定义Next.js服务器时触发,仓库根目录workspace.json配置了"customServerPath": "/src/server.ts"。克隆测试仓库后执行npm install,运行nx serve nextjs,点击"GO TO ABOUT"链接即可复现。
解决方案
方案1:调整Next.js的webpack配置,正确处理Swiper的ES模块
在Next.js项目的next.config.js(Nx项目一般在apps/[你的Next应用名]/next.config.js)中添加webpack规则,强制把Swiper的.mjs文件按ES模块处理:
// apps/[你的Next应用名]/next.config.js const { withNx } = require('@nx/next'); module.exports = withNx({ webpack: (config, { isServer }) => { // 仅针对服务器端打包配置 if (isServer) { config.module.rules.push({ test: /swiper\/.+\.mjs$/, type: 'javascript/auto', }); } return config; }, });
这个配置让webpack不会把Swiper的ES模块转成CommonJS,避免require加载报错。
方案2:将自定义服务器改为ES模块格式
如果自定义服务器不需要兼容CommonJS环境,可以直接改成ES模块:
- 把
src/server.ts重命名为src/server.mts(或.mjs) - 修改
workspace.json里的customServerPath为"/src/server.mts" - 服务器文件里全部用
import替代require语法 - 若全局需要ES模块支持,在项目根目录
package.json中加"type": "module";单文件启用的话,在服务器文件顶部加"use strict"; import.meta.url;
方案3:配置Nx转译排除规则
在nx.json或项目的tsconfig.json中,把Swiper相关模块加入转译排除列表:
// nx.json { "targetDefaults": { "build": { "options": { "transpilePackages": ["swiper", "swiper/react", "swiper/modules"] } } } }
或者在项目的tsconfig.json中:
{ "compilerOptions": { "skipLibCheck": true, "esModuleInterop": true }, "exclude": ["node_modules/swiper/**/*"] }
这样Nx在转译时会跳过Swiper模块,直接使用它的原生ES模块格式。
内容的提问来源于stack exchange,提问作者DevOverflow
相关产品推荐
相关产品推荐

