React

Storybook에 tailwindcss 적용하기

래모 2024. 10. 8. 14:29

이제 tailwind없이는 css 구성을 못 해버리는 지경에 와버린 나...

storybook을 사용하면서도 tailwind를 사용하고 싶었는데 버튼 자체의 className에 tailwind를 적용하니 아래와 같이 적용되지 않았다

 

반면 일반 컴포넌트에 버튼을 불러와 사용해보니 아래와 같이 잘 적용된 모습!

 

참고로 이때 코드는 아래와 같다

// App.tsx
import { Button } from "./components/Button"

function App() {


  return (
    <>
      <Button label="하윙?" />
    </>
  )
}

export default App


//components/Button.tsx
import React from 'react';


export interface ButtonProps {
  primary?: boolean;
  backgroundColor?: string;
  size?: 'small' | 'medium' | 'large';
  label: string;
  onClick?: () => void;
}

/** Primary UI component for user interaction */
export const Button = ({
  primary = false,
  size = 'medium',
  backgroundColor,
  label,
  ...props
}: ButtonProps) => {
  const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
  return (
    <button
      type="button"
      className={`border p-2 rounded-lg `}
      {...props}
    >
      {label}
    </button>
  );
};

 

 

왜이러지 왜이러지 찾아보다가

적용 범위 제한문제라는 것을 알아냈다

 

index.css에는 tailwind파일을 import 하였다.

App.tsx는 index.css 아래에 적용되므로 tailwind가 적용이 되지만

storybook에는 index.css 하위에 있지 않기 때문에 한 번 더 tailwind파일을 임폴트 해주어야 하는 것이다

 

 

따라서, 컴포넌트에 css파일을 import 해주고 css 파일에 아래를 적용해주면 storybook에서도 tailwind가 정상 작동한다.

//components/Button.tsx
import React from 'react';
import "./button.css"

export interface ButtonProps {
  primary?: boolean;
  backgroundColor?: string;
  size?: 'small' | 'medium' | 'large';
  label: string;
  onClick?: () => void;
}

/** Primary UI component for user interaction */
export const Button = ({
  primary = false,
  size = 'medium',
  backgroundColor,
  label,
  ...props
}: ButtonProps) => {
  const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
  return (
    <button
      type="button"
      className={`main-button`}
      {...props}
    >
      {label}
    </button>
  );
};


//components/button.css
@tailwind base;
@tailwind components;
@tailwind utilities;

.main-button {
  @apply border p-2 rounded-lg
}

 

된당!

 

 

** 모든 css 파일마다 tailwind를 임폴트 해주기 귀찮으면

stories/previes.tsx에 index.css를 임폴트 해주면 모든 storybook에 적용이 된다.

 

import type { Preview } from "@storybook/react";
import "../src/index.css"

const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
  },
};

export default preview;