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:
如果你使用Next.js 11.x版本,先安装转译依赖:/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['swiper', 'ssr-window', 'dom7'], // 保留你原有其他配置 } module.exports = nextConfig
再修改npm install next-transpile-modules --save-devnext.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
相关产品推荐
相关产品推荐

