Don't think! Just do it!

종합 IT 기술 정체성 카오스 블로그! 이... 이곳은 어디지?

Next.js

Next.JS 프로젝트 기본 템플릿 만들기#2

방피터 2022. 6. 15. 14:22

next.js 기본 템플릿 만들기 계속해봅시당

2022.06.14 - [Next.js] - Next.JS 프로젝트 기본 템플릿 만들기#1

 

Next.JS 프로젝트 기본 템플릿 만들기#1

nextjs 말고도 이런 저런 것들이 많이 필요한 것 같아. 기본적으로 ui framwork도 하나 있어야 할 것 같고 tailwindcss도 사용하고 싶고 storybook도 사용하면 좋을 것 같고 .env.local, .npmrc, .nvmrc 파일도 만..

engschool.tistory.com

저번에 .nvmrc, .npmrc 만들고 package.json 수정했어. 그리고 mui 설치하고 SSR을 위한 _app.tsx, _document.tsx 도 생성/수정 했고 이제 tailwindcss 설치만 하면 내가 원하는 환경은 거의 완성이 되는 것 같아. 그리고 나면 내 하찮은 머리만 준비되면 되겠네 ㅋㅋ

 

tailwindcss 멋있당~ 우왕

tailwindcss를 굳이 쓰려고 하는 이유? 음 글쎄 사실 잘 몰라. 뭐랄까 css에 좀 자신이 없거든.. 잘 이해도 안되고 ㅋㅋ 그래서 남들이 잘 만들어 놓은거 쓰고 싶은 것도 있고 ㅎㅎ 어차피 잘 못하는 거 공부할 거면 새로 나온거 하는게 좋을 거 같아서 ㅎㅎㅎㅎ 그리고 css 파일 구조랄까? 변수랄까 이걸 다 외울수도 없고 이름정하는 것도 스트레스고 미치겠더라고!

나만 그런거 아니잖아 ㅋㅋ

그런데 tailwindcss는 뭐 클래스 이름 뭐 이딴거 없으니까 너무 편할 것 같은 느낌. 대신 컴포넌트에 주르륵 쓰니까 코드가 너무 지저분해지긴 하지. 근데 emotion styled이나 styled-components랑 같이 사용하면 지저분한 코드 문제도 싹 사라지는 것 같아서 너무 행복. 뭐랄까 드디어 코드짜는 거 같은 느낌이 든다랄까? 이걸 같이 함 해보자구!

메뉴얼 볼 사람들은 참고하시고 👉 https://tailwindcss.com/docs/guides/nextjs

 

Install Tailwind CSS with Next.js - Tailwind CSS

Documentation for the Tailwind CSS framework.

tailwindcss.com

자 설치 시작. npm 안쓰기로 한거 기억나지? npm 사용하면 이제 오류가 날겨~ yarn을 쓰자고~

yarn add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

이렇게 하면 tailwind.config.js 파일 생기는데 아래처럼 모든 Path 다 넣어주면 끝.

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

그리고 index.tsx에 tailwindcss를 사용한 <a> 컴포넌트를 추가해보자구 

<a className="text-5xl text-red-500 underline">TailwindCss!</a>

ㅎㅎ 그럼 아래 그림처럼 나와! 맞아 아무런 변화가 없지! 일단 우리는 저번시간에 global css import를 다 날렸어. 그래서 tailwindcss가 글로벌하게 적용되지 않는 거야.

tailwindcss가 적용되지 않는다.

그렇다고 global css를 다시 _app.tsx에 import하면 컴포넌트에 다이렉트로 넣은 tailwindcss가 적용되지만 mui가 없어지는 아름다운 결과를 볼 수 있지 ㅎㅎ

MUI 스타일이 없어졌다!

어쨋든 우리는 mui을 사용하면서 emotion/styled + tailwindcss가 목적이니까 걍 밀어붙여보자고 ㅎㅎ emotion/styled component에서 tailwindcss를 사용이 가능하도록 해주는 twin.macro라는 녀석이 있어.

 

1. twin.macro 설치해보자구.

yarn add twin.macro

2. package.json에 babelMacros twin 옵션 추가.

3. types folder 생성 -> twin.d.ts 파일 생성 👇

import 'twin.macro'
import { css as cssImport } from '@emotion/react'
import { CSSInterpolation } from '@emotion/serialize'
import styledImport from '@emotion/styled'

declare module 'twin.macro' {
  // The styled and css imports
  const styled: typeof styledImport
  const css: typeof cssImport
}

declare module 'react' {
  // The css prop
  interface HTMLAttributes<T> extends DOMAttributes<T> {
    css?: CSSInterpolation
  }
  // The inline svg css prop
  interface SVGProps<T> extends SVGProps<SVGSVGElement> {
    css?: CSSInterpolation
  }
}

4. .babelrc.js 생성 👇

module.exports = {
  presets: [
    [
      "next/babel",
      {
        "preset-react": {
          runtime: "automatic",
          importSource: "@emotion/react",
        },
      },
    ],
  ],
  plugins: ["@emotion/babel-plugin", "babel-plugin-macros"],
};

음... 설정은 끝난거 같은데? 이 설정은 twin macro next example github repogitory 참고했어.👇

https://github.com/ben-rogerson/twin.examples/tree/master/next-emotion-typescript

 

GitHub - ben-rogerson/twin.examples: Packed with examples for different frameworks, this repo helps you get started with twin a

Packed with examples for different frameworks, this repo helps you get started with twin a whole lot faster. - GitHub - ben-rogerson/twin.examples: Packed with examples for different frameworks, th...

github.com

자 그럼 컴포넌트 하나 만들어 보자구 components 폴더 하나 생성하고 MyButton.tsx 파일 하나 만들고 👇

import React from "react";
import { Button, ButtonProps } from "@mui/material";
import tw, { styled } from "twin.macro";

//mui 버튼 스타일을 extends!
const MyButton = styled(Button)((props: ButtonProps) => [tw``]);

export default MyButton;

index.tsx에서 만든 버튼 추가하자.

import MyButton from "../components/Mybutton";
...
  <div>
    <MyButton>TailwindCss!</MyButton>
  </div>
...

웹 브라우저에서 새로 생긴 MUI 버튼을 볼 수 있지. 저 버튼에 tailwindcss 옵션을 줘보자구!

Twin.macro styled component 적용!

잘 몰라서 아무거나 막 넣어봤어! tw`` 사이에 tailwindcss 넣어주면 돼.

import React from "react";
import { Button, ButtonProps } from "@mui/material";
import tw, { styled } from "twin.macro";

const MyButton = styled(Button)((props: ButtonProps) => [
  tw`
    text-blue-400
    border-purple-500
    text-5xl
    shadow-md
    rounded-xl
`,
]);

export default MyButton;

이제 아래와 같이 MUI가 적용된 Button을 볼 수가 있지.

tailwindcss 적용된 MUI button

그런데 여기 사소한 문제가 하나 있어. globalcss 를 import하지 않아도 컴포넌트에 className을 사용하지 않고 twin.macro의 tw를 사용하면 tailwindcss가 컴포넌트에 바로 적용되게 할 수 있어. 하지만!

  <div>
    <a tw="text-5xl text-red-500 underline">TailwindCss!</a>
  </div>

스토리북에서는 적용이 되지가 않아. emotion styled component로 만든 버튼만 정상적으로 보이지.

스토리북

이것도 스토리북에서 적용되어야 하나? 모르겠다 ㅋ 걍 emotion styled만 사용하는 strict 모드 개발을 하기 위해서 좋을지도 모르겠어 ㅋㅋㅋ 그래 괜히 중간에 style 막 껴넣지 말고 component driven!!! 하자고!

 

이제 스토리북에 만들 버튼만 따로 넣어보자구. stories폴더에 components 폴더를 새로 하나 만들고 MyButton.stories.tsx 파일을 생성!

스토리북에 새 컴포넌트 만들기

아래 코드 입력👇

import { ComponentStory } from "@storybook/react";
import MyButton from "../../components/Mybutton";

export default {
  title: "Components/Button",
  component: MyButton,
};

const Template: ComponentStory<typeof MyButton> = (args) => (
  <MyButton {...args} />
);
export const Button_Default = Template.bind({});
Button_Default.args = {
  children: <a>Button</a>,
};

 

스토리북 Components 카테고리에 MyButton를 추가했고 children에 <a>Button</a> 넣어줘서 Button이라는 글씨와 함께 버튼이 출력되겠지. 왜냐면 MyButton 컴포넌트 만들때 그냥 default children없이 깡 export해서 스토리북에는 네모칸만 보이거든.. 이런 방식이 맴에 안들면 애당초 버튼 컴포넌트 만들 때 버튼 텍스트 지정할 수 있도록 해도 되고.. 이건 뭐 너무 방식이 다양해서 이 정도로만 하자고. 암튼 이렇게 하고 나면! 👇👇👇👇

스토리에 MyButton 뙇!

 

휴우 이제 설치할 것들은 모두다 끝이 난 듯. 이제 git push 하고... 음 이 다음부턴 실제로 프로젝트를 진행해보도록 하자구. 마침 해야할 일이 있으니 아래는 github 주소야. ㅎㅎㅎ 니들이 필요할 진 모르겠다만 필요한 친구들 가져다 쓰시고~

https://github.com/peter-bang/nextjs-basic-configuration

 

GitHub - peter-bang/nextjs-basic-configuration: nextjs basic configurations

nextjs basic configurations. Contribute to peter-bang/nextjs-basic-configuration development by creating an account on GitHub.

github.com

 

기본적으로 추가할 게 생기면 블로그를 또 쓰도록 하지! 안녕!

반응형