Nextjs + typescript +styled-components

요약



1 - Add Typescript
2 - Install styled-components
3 - Apply globalStyle
4 - Bonus 1 - Absolute imports
5 - Bonus 2 - SSR with stylesheet rehydration

길을 잃으면 https://github.com/rffaguiar/setup-nextjs-typescript-styled-components에서 모든 코드를 사용할 수 있습니다.

당신은 또한 트위터에서 나에게 도달할 수 있습니다.

계속하자!

https://nextjs.org/learn/basics/create-nextjs-app에서 Next.js를 배우기 시작했습니다. 이제 멋진 앱을 직접 구축하고 싶을 것입니다. 작은 자습서에서는 스타일 구성 요소, typescript 또는 전역 스타일을 추가하는 방법을 가르치지 않았습니다. 걱정하지 마세요. 아기가 이것들을 밟게 해주세요.

주의: 이 설정에는 다음 패키지 버전이 사용되었습니다.

"dependencies": {
    "next": "9.4.4",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "styled-components": "^5.1.1"
  },
  "devDependencies": {
    "@types/node": "^14.0.9",
    "@types/react": "^16.9.35",
    "babel-plugin-styled-components": "^1.10.7",
    "typescript": "^3.9.3"
  }

타입스크립트 추가

Rename any of your .js to .tsx . Go ahead and rename your index.js to index.tsx and try to start your server. You will receive an error on CLI that you're trying to use Typescript but you don't have the necessary packages. Run:

npm install --save-dev typescript @types/react @types/node

When you start the server after the ts packages, 2 files are created for you: next-env.d.ts and tsconfig.json .

  • next-env.d.ts : Nextjs type declaration file referencing its types inside of your node_modules/next/types/global
  • tsconfig.json : contains the compiler options required to compile the project and specifies the root.

Your typescript is ready.

스타일 구성 요소 설치

npm install --save styled-components

For testing purposes, make your index.tsx like this:

import styled from "styled-components";

const Title = styled.h1`
  color: red;
`;

const Home = () => {
  return (
    <div>
      <p>hello</p>
      <Title>Title</Title>
    </div>
  );
};

export default Home;

Go to the browser and inspect the Title (h1) element.



className이 얼마나 끔찍한지 보십니까? .sc-AxjAm.gxygnu 확실히 설명이 아닙니다!

그렇기 때문에 babel 플러그인을 함께 설치하는 것을 권장합니다.

npm install --save-dev babel-plugin-styled-components

다음을 사용하여 프로젝트의 루트에 파일.babelrc을 생성합니다.

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

서버를 다시 시작하고 요소를 다시 검사하십시오.



꽤 멋지죠? 이제 className이 훨씬 더 설명적입니다.
babel 플러그인은 styled-components + Nextjs에 더 많은 파워업을 제공합니다.
  • 소형 번들
  • 서버측 렌더링 호환성
  • 디버깅 개선
  • 축소
  • 데드 코드 제거

  • globalStyle 적용

    Cool! Now you have an incredible JS framework with a powerful style system. But...wait, what if you wanted to reset and/or share styles across all of your pages? Here we go with styled-components' globalStyle .

    First, let's start with a Layout component. This is going to wrap every page and has all the shared styles.

    Outside the /pages directory, create another folder /layout with Basic.tsx inside:

    # /layout
    # --/Basic.tsx
    # /pages
    # --/index.tsx
    

    Inside of Basic.tsx you include and return your shared styles. The trick here is to include the createGlobalStyle and return it on Basic.tsx render.

    import { createGlobalStyle } from "styled-components";
    
    export const GlobalStyle = createGlobalStyle`
        // this is the shared style
      html {
        box-sizing: border-box;
      }
    
      *,
      *::before,
      *::after {
        box-sizing: inherit;
      }
    
    h1 {
        color: yellow !important; // the important is just to show that the style works!
    }
    
      // anything else you would like to include
    `;
    
    const BasicLayout = ({ children }: { children: any }) => {
      return (
        <>
          <GlobalStyle />
          {children}
        </>
      );
    };
    
    export default BasicLayout;
    

    Returning to pages/index.tsx . Import the newly created BasicLayout component and wrap the Home returned React element with BasicLayout.

    import styled from "styled-components";
    import BasicLayout from "../layout/Basic";
    
    const Title = styled.h1`
      color: red;
    `;
    
    const Home = () => {
      return (
        <BasicLayout>
          <p>hello</p>
          <Title>Title</Title>
        </BasicLayout>
      );
    };
    
    export default Home;
    

    From now on, all the pages that include BasicLayout components are going to inherit the styles.

    Congratulations!!! Now you have a proper Nextjs + Typescript + styled-component with global styles working!

    보너스 1 - 절대 수입

    By default Nextjs allows you to use relative imports. You know, those never-ending imports ../../../../finally.tsx . If you want to use an absolute import, you have to change just one line on tsconfig.json : the baseUrl .

    "compilerOptions": {
        // other options
        "baseUrl": "."
      },
    

    Now, all absolute imports start at the same level as the tsconfig.json file. Using the previous pages/index.tsx import as an example, you can change A to B.

    // A
    import BasicLayout from "../layout/Basic";
    
    // B
    import BasicLayout from "layout/Basic";
    
    

    보너스 2 - 스타일시트 리하이드레이션이 포함된 SSR

    The fancy term which means: serve the required styles for the first render within the HTML and then load the rest in the client.

    You need to create a custom /pages/_document.tsx and copy the following logic into it. That's it.

    import Document from 'next/document'
    import { ServerStyleSheet } from 'styled-components'
    
    export default class MyDocument extends Document {
      static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheet()
        const originalRenderPage = ctx.renderPage
    
        try {
          ctx.renderPage = () =>
            originalRenderPage({
              enhanceApp: (App) => (props) =>
                sheet.collectStyles(<App {...props} />),
            })
    
          const initialProps = await Document.getInitialProps(ctx)
          return {
            ...initialProps,
            styles: (
              <>
                {initialProps.styles}
                {sheet.getStyleElement()}
              </>
            ),
          }
        } finally {
          sheet.seal()
        }
      }
    }
    
    The code above was taken directly from the styled-components example on nextjs github repo .

    좋은 웹페이지 즐겨찾기