CRA에서 Swiper 사용하기

야채·2021년 12월 28일
0

제가 겪었던 것처럼, 누군가 CRA 환경에서 Swiper를 사용하는데 공식 사이트 예제처럼 안되고 import 오류가 난다면 이 포스팅이 조금이나마 도움이 되길 바라는 마음에서 작성했습니다.

영화 API를 가지고 React + TS를 연습하면서 영화 포스터들을 carousel slider로 보여주고 싶었습니다.

그래서 slider를 쉽게 만들 수 있도록 도와주는 swiper를 이용해서 carousel을 만들어보기로 했습니다.

Swiper 공식 홈페이지
공식홈페이지 내 React 환경에서 Swiper 사용 설명

다행히 swiper은 따로 swiper에 대한 타입스크립트 패키지를 설치할 필요없이

npm i swiper

swiper 만 설치해도 TypeScript 환경에서 사용이 가능합니다.

React 카테고리에서 Usage 항목을 보면 아래와 같이 예시가 나와있습니다.

// Import Swiper React components
import { Swiper, SwiperSlide } from 'swiper/react';

// Import Swiper styles
import 'swiper/css';

export default () => {
  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>
  );
};

그런데 저는 CRA를 통해 리액트 환경을 구축했기 때문에 다른 방법으로 swiper를 import해서 사용해야 했습니다.

Usage with Create React App 항목에서는 다른 예제를 보여주고 있습니다.

Create React App doesn't support pure ESM packages yet.
It is still possible to use Swiper (7.2.0+) with it.
In this case we need to use direct file imports:

CRA(Create React App)에서는 순수 ESM 패키지를 아직 지원하지 않는다. 7.2.0 이상 버전의 Swiper은 사용이 가능하다. 이러한 경우 (아래 예제와 같이) 파일에서 직접 import를 해와야 한다.

라고 설명이 되어있습니다.

// Core modules imports are same as usual
import { Navigation, Pagination } from 'swiper';
// Direct React component imports
import { Swiper, SwiperSlide } from 'swiper/react/swiper-react.js';

// Styles must use direct files imports
import 'swiper/swiper.scss'; // core Swiper
import 'swiper/modules/navigation/navigation.scss'; // Navigation module
import 'swiper/modules/pagination/pagination.scss'; // Pagination module

이걸 그대로 복사해와서 사용했고, swiper에서 제공하는 navigation이나 pagination의 기본적인 스타일을 쓰고 싶다면 추가적으로 scss를 사용할 수 있도록 환경을 만들어줘야 합니다.

npm i sass

sass를 추가적으로 설치해주고 바로 적용이 안된다면 재실행해보면 적용이 됩니다.

아래와 같은 코드를 이용해서 위 사진처럼 carousel slider를 만들었습니다.


import { Swiper, SwiperSlide } from 'swiper/react/swiper-react.js';
import { Autoplay, EffectCoverflow } from 'swiper';

import 'swiper/swiper.scss'; // core Swiper

<Swiper
  modules={[Autoplay, EffectCoverflow]}
  grabCursor={true}
  centeredSlides={true}
  effect='coverflow'
  style={{ height: '360px' }}
  coverflowEffect={{
    rotate: 10,
  }}
  loop={true}
  spaceBetween={50}
  slidesPerView={4}
  autoplay={{ delay: 1000 }}
>
  {nowPlaying &&
    nowPlaying.map((movie) => {
      return (
        <SwiperSlide key={movie.id}>
          <Cover bgImg={`https://image.tmdb.org/t/p/original${movie.poster_path}`}></Cover>
        </SwiperSlide>
      );
    })}
</Swiper>

swiper 홈페이지에 가면 제가 구현한 것 말고도 다른 slider 종류들이 정말 많습니다. 제 코드를 보시면 아시겠지만 필요한 효과가 있으면 Swiper component에 import해온 효과들을 modules라는 property에 배열 형태로 추가해주고, Swiper component에 있는 여러 property를 통해 스타일링이나 효과들을 바꿔줄 수 있습니다.

효과들에 대한 설명은 Swiper Effect 에 들어가보면 예제와 함께 샌드박스 코드도 함께 제공하므로 어떤 것들이 있는지 살펴보고 필요한 부분을 쓰면 될 것 같습니다.

carousel slider 자체가 정말 많은 웹사이트에서 구현되어 있어서 원리가 궁금해 직접 만들기도 해봤고, 쉽게 slider를 만들어주는 swiper을 한 번쯤은 꼭 사용해봐야겠다고 이전부터 생각했었습니다.

처음에 공식 사이트 예제가 잘 나와있어서 가져와 썼는데 import 에러가 나서 당황했지만, 구글링과 공식 사이트를 다시 보면서 곧 CRA 환경에서는 다른 방법으로 사용해야된다는 것을 알고 나서는 쉽게 사용할 수 있었습니다.

어떠한 기능을 설치해서 쓸 때 오류가 날 때는, 답은 웬만하면 공식 사이트 문서에 있으므로 예제가 있다고 방심하지말고 꼼꼼히 보는 습관을 들여야겠다고 다시 한 번 생각했습니다. 헤헤 😅

profile
코딩하는 야채

0개의 댓글