본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Flowbite + Nuxt

원문 보기 위키 갱신

Nuxt는 Vue.js 기반의 무료·오픈소스 JavaScript 프레임워크예요. SSR(서버 사이드 렌더링)을 사용해 현대적인 웹 애플리케이션을 개발할 수 있게 해주고, 더 빠른 로드, 더 나은 SEO, 더 나은 캐싱을 제공해요. Vercel의 React 기반 Next.js 프레임워크에서 영감을 받았으며, Ecosia, Upwork, NASA, Appsumo, CDN JS 같은 대기업에서 사용하고 있어요.

출처: 문서

본문

이 가이드를 따라 Tailwind CSS v4와 Flowbite와 함께 Nuxt 3 최신 버전을 설치하고, TypeScript 버전을 사용하는 법도 배워요.

Nuxt 프로젝트 만들기 (Create a Nuxt project)

계속하기 전에 로컬 머신에 Node.js와 NPM이 설치되어 있어야 해요.

터미널에서 다음 명령을 실행해 새 Nuxt 프로젝트를 만들어요.

npx nuxi init flowbite-app
cd flowbite-app

프로젝트 의존성을 설치해요.

npm install

다음 명령으로 http://localhost:3000/ 에 로컬 개발 서버를 시작해요.

npm run dev

그러면 브라우저에서 Nuxt 프로젝트에 접근할 수 있어요.

Tailwind CSS 설치 (Install Tailwind CSS)

Nuxt 프로젝트를 로컬에 설정했으니 Tailwind CSS를 설치해보아요.

NPM으로 Tailwind CSS와 Vite 플러그인을 설치해요.

npm install tailwindcss @tailwindcss/vite --save

Nuxt 구성 파일에 Tailwind 모듈을 포함하도록 설정해요.

import tailwindcss from "@tailwindcss/vite";

export default defineNuxtConfig({
  devtools: { enabled: true },
  css: ['~/assets/css/input.css'], // you'll have to create this file
  vite: {
    plugins: [
      tailwindcss(),
    ],
  },
});

./assets/css/input.css라는 새 CSS 파일을 만들고 Tailwind를 가져와요.

@import "tailwindcss";

이제 프로젝트에 Tailwind CSS가 구성되었어요. Vue 템플릿 파일 어디에서든 유틸리티 클래스를 추가하면 CSS가 생성되어 포함돼요.

Flowbite 설치 (Install Flowbite)

Nuxt와 Tailwind CSS를 모두 설치했으니 Flowbite를 설치해보아요.

NPM으로 Flowbite를 의존성으로 설치해요.

npm install flowbite --save

메인 input.css CSS 파일에 Flowbite의 기본 테마 변수를 가져와요.

/* choose one of the following */

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
@import "flowbite/src/themes/default";

/* MINIMAL THEME
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300..800;1,300..800&display=swap');
@import "flowbite/src/themes/minimal";
*/

/* ENTERPRISE THEME
@import url('https://fonts.googleapis.com/css2?family=Shantell+Sans:ital,wght@0,300..800;1,300..800&display=swap');
@import "flowbite/src/themes/enterprise";
*/

/* PLAYFUL THEME
@import url('https://fonts.googleapis.com/css2?family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&display=swap');
@import "flowbite/src/themes/playful";
*/

/* MONO THEME
@import "flowbite/src/themes/mono";
*/

CSS에 Flowbite 플러그인 파일을 가져와요.

@plugin "flowbite/plugin";

CSS에 Flowbite의 소스 파일 경로를 구성해요.

@source "../../node_modules/flowbite";

Flowbite 컴포넌트 (Flowbite components)

Nuxt, Tailwind CSS, Flowbite를 성공적으로 설치했다면 이제 Flowbite 오픈소스 라이브러리의 컴포넌트(모달, 네비게이션 바, 테이블, 드롭다운 등)를 가져와 사용할 수 있어요.

예시로 Modal 컴포넌트를 사용해서 문서의 마크업을 app.vue 페이지에 복사·붙여넣어보아요.

<template>
    <div>
        <div class="flex justify-center p-4">
            <button id="button" data-modal-toggle="modal" data-modal-target="modal" type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Show modal</button>
        </div>
        <div id="modal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full">
            <div class="relative w-full max-w-2xl max-h-full">
                <!-- Modal content -->
                <div class="relative bg-white rounded-lg shadow-sm dark:bg-gray-700">
                    <!-- Modal header -->
                    <div class="flex items-start justify-between p-5 border-b rounded-t dark:border-gray-600">
                        <h3 class="text-xl font-semibold text-gray-900 lg:text-2xl dark:text-white">
                            Terms of Service
                        </h3>
                        <button id="closeButton" data-modal-hide="modal" type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white">
                            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>  
                        </button>
                    </div>
                    <!-- Modal body -->
                    <div class="p-6 space-y-6">
                        <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
                            With less than a month to go before the European Union enacts new consumer privacy laws for its citizens, companies around the world are updating their terms of service agreements to comply.
                        </p>
                        <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
                            The European Union's General Data Protection Regulation (G.D.P.R.) goes into effect on May 25 and is meant to ensure a common set of data rights in the European Union. It requires organizations to notify users as soon as possible of high-risk data breaches that could personally affect them.
                        </p>
                    </div>
                    <!-- Modal footer -->
                    <div class="flex items-center p-6 space-x-2 border-t border-gray-200 rounded-b dark:border-gray-600">
                        <button type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">I accept</button>
                        <button type="button" class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-blue-300 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600">Decline</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

데이터 속성 (Data attributes)

Nuxt의 onMounted 생명주기 메서드를 사용해 Flowbite 패키지에서 init 함수들을 가져오면 인터랙티브 컴포넌트를 자동으로 동작하게 할 수 있어요. 클라이언트 사이드 JavaScript가 페이지가 완전히 로드된 후에만 실행되도록 보장해야 해요. 그래서 composables 폴더 안에 useFlowbite.js 파일을 만드는 걸 권장해요.

// composables/useFlowbite.js

export function useFlowbite(callback) {
  if (process.client) {
    import('flowbite').then((flowbite) => {
      callback(flowbite);
    });
  }
}

SSR을 사용한다면 Nuxt 애플리케이션에서 Flowbite를 가져오는 유일한 방법이 이거여야 해요. 그렇게 해야 서버 사이드에서 document 객체가 없어도 되는 문제를 막을 수 있어요. 그다음 Nuxt 페이지 안에서 useFlowbite 함수를 가져와 컴포넌트를 초기화해요.

<script setup>
import { onMounted } from 'vue'
import { useFlowbite } from '~/composables/useFlowbite';

// initialize components based on data attribute selectors
onMounted(() => {
    useFlowbite(() => {
        initFlowbite();
    })
})
</script>

<template>
    // Modal HTML markup with data attributes from Flowbite
</template>

혹은 컴포넌트를 각각 초기화할 때 사용할 수 있는 전체 함수 목록을 쓸 수도 있어요.

<script setup>
import { onMounted } from 'vue'
import { useFlowbite } from '~/composables/useFlowbite';
import { 
    initAccordions, 
    initCarousels, 
    initCollapses, 
    initDials, 
    initDismisses, 
    initDrawers, 
    initDropdowns, 
    initModals, 
    initPopovers, 
    initTabs, 
    initTooltips } from 'flowbite'

// initialize components based on data attribute selectors
onMounted(() => {
    useFlowbite(() => {
        initAccordions();
        initCarousels();
        initCollapses();
        initDials();
        initDismisses();
        initDrawers();
        initDropdowns();
        initModals();
        initPopovers();
        initTabs();
        initTooltips();
    })
})
</script>

이렇게 하면 Flowbite의 데이터 속성으로 모든 인터랙티브 컴포넌트가 동작하지만, 로드 속도를 최적화하려면 실제로 각 페이지에서 사용하는 컴포넌트만 초기화하는 걸 권장해요. 실제 동작은 스타터 가이드의 Events.vue 파일에서 확인할 수 있어요.

JavaScript API

컴포넌트를 인터랙티브하게 만들려면 Flowbite에서 Modal 객체를 가져와 객체 파라미터, 옵션, 메서드를 설정해서 버튼 클릭에 따라 모달을 보여주거나 숨겨야 해요.

<script setup>
import { onMounted } from 'vue'
import { Modal } from 'flowbite'
import { useFlowbite } from '~/composables/useFlowbite';

onMounted(() => {
    useFlowbite(() => {
        // setup available elements
        const $buttonElement = document.querySelector('#button');
        const $modalElement = document.querySelector('#modal');
        const $closeButton = document.querySelector('#closeButton');

        // set modal options
        const modalOptions = {
            backdropClasses: 'bg-gray-900/50 dark:bg-gray-900/80 fixed inset-0 z-40'
        }

        // create a new modal instance
        if ($modalElement) {
            const modal = new Modal($modalElement, modalOptions);

            // set event listeners for the button to show the modal
            $buttonElement.addEventListener('click', () => modal.toggle());
            $closeButton.addEventListener('click', () => modal.hide());

        }
    })
})
</script>

보시다시피 Vue 3의 onMounted() 생명주기 메서드를 사용해 모달 컴포넌트를 만드는 데 필요한 요소를 쿼리하고, 프로그래밍 방식으로 모달을 보여주거나 숨기는 메서드를 사용해요.

// add your own logic and then show the modal
modal.show();

// or you can hide it
modal.hide();

JavaScript가 필요한 모든 인터랙티브 컴포넌트 페이지에는 사용 가능한 파라미터, 옵션, 메서드를 보여주는 Flowbite 문서가 있어요.

타입 사용 (Using types)

Flowbite는 v1.6.0부터 TypeScript도 지원해요. JavaScript API의 객체, 파라미터, 옵션 값에 대한 타입 선언과 인터페이스를 사용할 수 있어요.

이렇게 타입이나 인터페이스를 가져올 수 있어요.

import { Modal } from 'flowbite'
import type { ModalOptions, ModalInterface } from 'flowbite'

// other code

일반적으로 모든 컴포넌트에는 인터페이스 정의가 있어서, 새 객체를 만들 때마다 올바른 타입의 파라미터와 메서드를 사용하고 있는지 확인할 수 있어요. 새 모달을 만들 때 ModalInterface를 메인 타입으로 설정할 수 있어요.

const modal: ModalInterface = new Modal($modalElement, modalOptions);

모든 Flowbite 컴포넌트는 옵션 객체에 대한 타입 선언도 지원해요. 예를 들면 다음과 같아요.

const modalOptions: ModalOptions = {
    placement: 'top-right'
}

const modal: ModalInterface = new Modal($modalElement, modalOptions);

타입 사용은 허용된 타입과 값을 옵션에만 쓰게 보장해주기 때문에 매우 유용해요. 예를 들어 placement 값에 색상인 yellow를 넣으면 TypeScript가 Flowbite의 타입 요구 사항에 맞지 않는다며 오류를 던져요.

다음은 TypeScript로 타입을 사용한 전체 코드예요.

import { Modal } from 'flowbite'
import type { ModalOptions, ModalInterface } from 'flowbite'

const $buttonElement: HTMLElement = document.querySelector('#button');
const $modalElement: HTMLElement = document.querySelector('#modal');

const modalOptions: ModalOptions = {
    placement: 'top-right'
}

const modal: ModalInterface = new Modal($modalElement, modalOptions);
$buttonElement.addEventListener('click', () => modal.toggle());

modal.show();

공식 문서 페이지에서 Flowbite를 TypeScript와 함께 사용하는 법을 더 배워요.

Nuxt 스타터 프로젝트 (Nuxt Starter Project)

Flowbite의 모든 인터랙티브 UI 컴포넌트를 보여주는 무료·오픈소스 Tailwind CSS & Nuxt 스타터 프로젝트를 만들었어요. 웹 애플리케이션 구축을 시작하는 데 도움이 돼요.

Flowbite Vue 라이브러리 (Flowbite Vue Library)

또한 독립적인 Flowbite Vue 3 UI 컴포넌트 라이브러리 작업을 시작했어요. 안정 버전으로 출시되면 Vue 3 또는 Nuxt 환경에서 작업하는 권장 방식이 될 거예요. 기여는 언제나 환영해요!

더 알아보기 (Learn more)