[Solved] Module not found: Can't resolve 'swiper/css'
Problem:
While working with swiper 7 in React project we faced an error which says,
Module not found: Can't resolve 'swiper/css'
The code of the component Test.js is given below,
import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; function Test() { 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> ); } export default Test;
Solution 1:
For the first solution, you can downgrade to swiper 6 to fix the error. To downgrade the swiper version first remove the swiper entirely and add version 6.8.4.
For npm:
npm install swiper@6.8.4
For yarn:
yarn add swiper@6.8.4
then import swiper-bundle.min.css and swiper.min.css on the top of your file and it should work. So the updated code will be,
import { Swiper, SwiperSlide } from "swiper/react";
import 'swiper/swiper-bundle.min.css'
import 'swiper/swiper.min.css'
<Swiper
spaceBetween={50}
slidesPerView={3}
centeredSlides
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>
Solution 2:
For swiper@7.3.1
, you have to change the import path. You have to import swiper in your component like this,
import React from 'react'
import { Pagination } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react/swiper-react'
import 'swiper/swiper.min.css'
import 'swiper/modules/pagination/pagination.min.css'
Solution 3:
In recent versions of Swiper, there is no longer a css folder. So, swiper/css no longer exists. But the scss file is available so you can simply adapt your import in this way import 'swiper/swiper.scss'; As you are on React you will also need the node-sass library. Try this
import 'swiper/swiper.scss';
Thank you for reading the article. If you have any suggestions please comment below.