You need to enable JavaScript to run this app. Next.js升级Swiper至7.0.7后出现Cannot find module 'swiper/react'报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Next.js升级Swiper至7.0.7后出现Cannot find module 'swiper/react'报错如何解决

问题原因

Swiper 7+ 仅提供ES模块导出,未兼容CommonJS规范,Next.js服务端渲染阶段默认使用CommonJS的require加载模块,因此先后出现找不到模块、Error: Not supported两类报错。

解决步骤

  • 配置模块转译规则
    如果你使用Next.js 12.1及以上版本,直接修改next.config.js:
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      transpilePackages: ['swiper', 'ssr-window', 'dom7'],
      // 保留你原有其他配置
    }
    module.exports = nextConfig
    
    如果你使用Next.js 11.x版本,先安装转译依赖:
    npm install next-transpile-modules --save-dev
    
    再修改next.config.js:
    const withTM = require('next-transpile-modules')(['swiper', 'ssr-window', 'dom7']);
    module.exports = withTM({
      // 保留你原有其他配置
    })
    
  • 修改Swiper导入方式
    Swiper强依赖浏览器API,无需参与服务端渲染,将原有Swiper组件的静态导入改为动态导入并关闭服务端渲染:
    import dynamic from 'next/dynamic'
    // 关闭SSR的动态导入
    const Swiper = dynamic(() => import('swiper/react').then(mod => mod.Swiper), { ssr: false })
    const SwiperSlide = dynamic(() => import('swiper/react').then(mod => mod.SwiperSlide), { ssr: false })
    
    export default function CategoriesBar() {
      return (
        <Swiper
          spaceBetween={50}
          slidesPerView={3}
          onSlideChange={() => console.log('slide change')}
          onSwiper={(swiper) => console.log(swiper)}
        >
          <SwiperSlide>Slide 1</SwiperSlide>
          <SwiperSlide>Slide 2</SwiperSlide>
          <SwiperSlide>Slide 3</SwiperSlide>
          <SwiperSlide>Slide 4</SwiperSlide>
        </Swiper>
      )
    }
    
  • 原有_app.js中的全局CSS导入import 'swiper/scss'无需修改,保持原样即可。
  • 清理项目根目录下的.next缓存文件夹,重启开发服务即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:36:03