Nuxt3 다크모드 적용하기

Nuxt3에서 다크모드를 적용하고 관리하는 방법을 알아보자.

필요한 모듈 설치

Nuxt3에서 다크모드를 사용하려면 @nuxtjs/color-mode 모듈을 설치해야 한다.

npx nuxi module add color-mode

nuxt.config.ts 설정

설치가 끝났으면 nuxt.config.ts 파일에서 모듈을 추가해야 한다.

export default defineNuxtConfig({
  modules: [
    '@nuxtjs/color-mode'
  ]
})

useColorMode()$colorMode 차이점

Nuxt에서 컬러 모드를 다룰 때는 useColorMode()$colorMode 두 가지 방법이 있다.

1. $colorMode

  • 템플릿(HTML)에서 바로 접근 가능
  • $colorMode.value를 사용해서 현재 컬러 모드를 가져올 수 있음
  • preference 값을 변경하면 컬러 모드가 바뀜

템플릿에서 다크모드 버튼을 만들 때 $colorMode.value를 활용할 수 있다.

<template>
  <button @click="$colorMode.preference = $colorMode.value === 'light' ? 'dark' : 'light'">
    <span v-if="$colorMode.value === 'light'">라이트 모드</span>
    <span v-else>다크 모드</span>
  </button>
</template>

2. useColorMode()

  • setup() 함수에서 접근할 때 사용
  • const colorMode = useColorMode()로 가져와야 함
  • colorMode.preference를 변경하면 컬러 모드가 바뀜

컴포넌트 내부에서 컬러 모드를 제어할 때 사용한다.

<script setup>
const colorMode = useColorMode();

const toggleColorMode = () => {
  colorMode.preference = colorMode.value === 'light' ? 'dark' : 'light';
};
</script>

useColorMode()를 직접 불러와서 사용하는 이유

$colorMode는 템플릿 안에서만 사용할 수 있기 때문에, 스크립트(setup 함수)에서 다루려면 useColorMode()를 사용해야 한다.

예를 들어, 다크모드를 자동으로 설정하는 로직을 추가하고 싶다면 useColorMode()를 활용해야 한다.

<script setup>
const colorMode = useColorMode();

// 사용자의 기본 설정을 확인하고 자동으로 변경
if (colorMode.value === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
  colorMode.preference = 'dark';
}
</script>

이렇게 하면 사용자의 OS 설정이 다크 모드라면 자동으로 다크 모드를 적용할 수 있다.

다크모드 토글 버튼 예제

위 내용을 바탕으로, 다크모드 토글 기능을 구현해보자.

<template>
  <header class="header">
    <div class="header__container">
      <pre>{{ $colorMode }}</pre>

      <!-- 우측 액션 영역 (검색, 테마 전환 등) -->
      <div class="header__actions">
        <!-- 테마 전환 버튼 -->
        <button class="header__theme-btn" @click="toggleColorMode">
          <span v-if="$colorMode.value === 'light'">라이트</span>
          <span v-else>다크</span>
        </button>
      </div>
    </div>
  </header>
</template>

<script setup>
const colorMode = useColorMode(); // Nuxt 제공 훅

const toggleColorMode = () => {
  colorMode.preference = colorMode.value === 'light' ? 'dark' : 'light';
};
</script>

다크모드 초기 설정

기본적으로 Nuxt는 시스템 설정을 따라가지만, 특정 모드를 기본값으로 설정하고 싶다면 nuxt.config.ts에서 colorMode 옵션을 설정하면 된다.

export default defineNuxtConfig({
  modules: ['@nuxtjs/color-mode'],
  colorMode: {
    preference: 'dark', // 기본 다크모드 설정
    fallback: 'light', // 감지할 수 없을 때 사용할 기본 모드
    classSuffix: '',
  }
})

이렇게 하면 웹사이트에 처음 접속했을 때 다크모드가 적용된다.

다크모드 스타일 적용

Nuxt에서는 컬러 모드에 따라 <html> 태그에 자동으로 클래스가 추가된다.

/* 라이트 모드 스타일 */
body {
  background-color: white;
  color: black;
}

/* 다크 모드 스타일 */
.dark body {
  background-color: black;
  color: white;
}

이제 다크모드를 적용한 Nuxt3 프로젝트를 만들 수 있다.

📌 공식 문서 참고: https://nuxt.com/modules/color-mode