Flowbite + TypeScript 통합
TypeScript는 코드의 확장성·유지관리성·가독성을 개선해 주는 무료 오픈소스 프로그래밍 언어예요. JavaScript에 선택적 정적 타입을 추가함으로써 이 기능을 제공합니다. 이 가이드에서는 Tailwind CSS와 Flowbite 라이브러리를 TypeScript와 함께 설정하는 방법을 배우고, 통합된 타입·인터페이스로 Tailwind 애플리케이션을 구동하는 Flowbite 컴포넌트 사용법을 살펴봅니다.
출처: 문서
본문
새 프로젝트 만들기 (Create a new project)
로컬 프로젝트에 TypeScript와 Tailwind CSS를 설치하는 다음 단계들을 따라 하세요. 계속하기 전에 Node.js가 로컬에 설치되어 있어야 합니다. 먼저 새 프로젝트를 만들고 루트 폴더에 package.json을 생성하기 위해 npm init을 실행합니다.
npm init
TypeScript 설치 (Install TypeScript)
NPM으로 TypeScript를 설치하고 프로젝트에 설정합니다. tsconfig.json 파일을 만들고 lib, outDir, sourceMap, declaration, noImplicitAny, module, target 등 각 옵션의 의미를 알 수 있어요. 그다음 src/index.ts에 간단한 코드를 작성해 컴파일러가 잘 동작하는지 확인합니다. Webpack 번들러를 설치하면 TypeScript 코드를 브라우저에서 지원하는 JavaScript로 컴파일하고 하나의 파일로 번들링할 수 있습니다.
npm install --save-dev typescript
npx tsc --init
{
"compilerOptions": {
"lib": ["dom", "es2015"],
"outDir": "./lib/cjs/",
"sourceMap": true,
"declaration": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"allowJs": true,
"moduleResolution": "node"
},
"include": ["src/**/*.ts*"],
"exclude": ["node_modules", "dist", "lib"]
}
const text: string = 'Hello TypeScript';
console.log(text);
npm i -D webpack webpack-cli typescript ts-loader
//webpack.config.js
const path = require('path');
module.exports = {
mode: "development",
devtool: "inline-source-map",
entry: {
main: "./src/index.ts",
},
output: {
path: path.resolve(__dirname, './dist'),
filename: "app-bundle.js" // <--- Will be compiled to this single file
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader"
}
]
}
};
npx webpack --watch
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./dist/output.css">
</head>
<body>
<h1 class="text-4xl">Hello Tailwind CSS!</h1>
<script src="./dist/app-bundle.js"></script>
</body>
</html>
npx tsc
npx tsc -m es6 --outDir lib/esm
npm install -D tailwindcss
Tailwind CSS 설치 (Install Tailwind CSS)
Tailwind CSS 패키지를 설치하고 src 안에 input.css 파일을 만들어 기본 지시문을 import 합니다. npx @tailwindcss/cli 명령으로 변경 시 자동 컴파일되는 watch 모드로 output.css를 생성하고, index.html에서 컴파일된 코드를 포함시킵니다.
npm install tailwindcss @tailwindcss/cli
@import "tailwindcss";
npx @tailwindcss/cli -i ./src/input.css -o ./src/output.css --watch
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./dist/output.css">
</head>
<body>
<h1 class="text-4xl">Hello Tailwind CSS!</h1>
<script src="./dist/app-bundle.js"></script>
</body>
</html>
Flowbite 설치 (Install Flowbite)
npm install flowbite로 Flowbite를 의존성으로 설치하고, input.css에서 기본 테마 변수를 import 하며 Flowbite 플러그인 파일과 소스 파일을 CSS에 설정합니다. 이렇게 하면 TypeScript 타입을 지원하는 Flowbite의 오픈소스 인터랙티브 컴포넌트를 사용할 수 있어요.
npm install 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";
*/
@plugin "flowbite/plugin";
@source "../node_modules/flowbite";
Flowbite 컴포넌트 (Flowbite components)
TypeScript, Tailwind CSS, Flowbite를 설정한 뒤 이 스택으로 확장 가능한 웹사이트를 구축할 수 있어요. Modal 컴포넌트를 예로 들면, HTML 마크업에 고유 ID를 추가한 뒤 index.ts에서 Modal 클래스를 import 해 버튼 클릭 시 modal.toggle()로 가시성을 토글하도록 이벤트 리스너를 설정합니다.
<button id="button" 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">Default</button>
<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 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>
import { Modal } from 'flowbite'
// select the two elements that we'll work with
const $buttonElement: HTMLElement = document.querySelector('#button');
const $modalElement: HTMLElement = document.querySelector('#modal');
// create a new modal component
const modal = new Modal($modalElement);
// toggle the visibility of the modal when clicking on the button
$buttonElement.addEventListener('click', () => modal.toggle());
// add your own logic and then show the modal
modal.show();
import { Modal } from 'flowbite'
import type { ModalOptions, ModalInterface } from 'flowbite'
// other code
const modal: ModalInterface = new Modal($modalElement, modalOptions);
const modalOptions: ModalOptions = {
placement: 'top-right'
}
const modal: ModalInterface = new Modal($modalElement, modalOptions);
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();
TypeScript 스타터 프로젝트 (TypeScript Starter Project)
위 설정을 사용해 몇 가지 사전 빌드된 스크립트와 예시를 갖춘 Tailwind CSS TypeScript 스타터 프로젝트를 GitHub에서 제공합니다. 더 빠르게 시작하는 데 도움이 됩니다.