next.js + typescript + material ui 설치

susu.J·2021년 3월 15일
2

https://noogoonaa.tistory.com/65

참고해서 다운로드 받았다..

그런 다음 해당 사이트 참고하여
https://medium.com/@gogl.alex/how-to-set-up-typescript-eslint-prettier-for-next-gatsby-c5330b4a9b7a

dependencies 를 install 함.
npm i --save-dev @types/node @types/react @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react prettier typescript eslint babel-plugin-module-resolver eslint-import-resolver-babel-module eslint-plugin-react-hooks

tsconfig.json 에는 해당 code를 붙여넣었다.

{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["es6", "dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "ESNEXT",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@components/*": ["./src/components/*"],
      "@api/*": ["./src/api/*"],
      "@models/*": ["./src/models/*"],
      "@screens/*": ["./src/screens/*"],
      "@hooks/*": ["./src/hooks/*"],
      "@services/*": ["./src/services/*"],
      "@constants": ["./src/constants.ts"],
      "@context/*": ["./src/context/*"],
      "@queries/*": ["./src/queries/*"],
      "@data/*": ["./src/data/*"],
      "@typeDefs/*": ["./src/types/*"],
      "@generated/*": ["./src/generated/*"],
      "@public/*": ["./public/*"],
      "@utils/*": ["./src/utils/*"],
      "@app/*": ["./src/app/*"],
      "@assets/*": ["./src/assets/*"]
    }
  },
  "exclude": ["node_modules"],
  "include": ["**/*.ts", "**/*.tsx", "next-env.d.ts", "next.config.js"]
}

.eslintrc.js

module.exports = {
  env: {
    browser: true,
    node: true,
    es2020: true,
  },
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
    },
  },
  plugins: ["@typescript-eslint", "react", "prettier"],
  extends: [
    "airbnb",
    "airbnb/hooks",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended",
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
    "prettier",
    "prettier/@typescript-eslint",
    "prettier/react",
  ],
  rules: {
    "react/jsx-filename-extension": [1, { extensions: [".ts", ".tsx"] }],
    "import/extensions": "off",
    "react/prop-types": "off",
    "jsx-a11y/anchor-is-valid": "off",
    "react/jsx-props-no-spreading": ["error", { custom: "ignore" }],
    "prettier/prettier": "error",
    "react/no-unescaped-entities": "off",
    "import/no-cycle": [0, { ignoreExternal: true }],
    "prefer-const": "off",
    // needed because of https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-use-before-define.md#how-to-use & https://stackoverflow.com/questions/63818415/react-was-used-before-it-was-defined
    "no-use-before-define": "off",
    "@typescript-eslint/no-use-before-define": [
      "error",
      { functions: false, classes: false, variables: true },
    ],
  },
  settings: {
    "import/resolver": {
      "babel-module": {
        extensions: [".js", ".jsx", ".ts", ".tsx"],
      },
      node: {
        extensions: [".js", ".jsx", ".ts", ".tsx"],
        paths: ["src"],
      },
    },
  },
};

.VSCode라는 폴더를 만들고, 그 안에 settings.json이라는 파일을 넣어주고 해당 코드를 붙였다.

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.formatOnSave": true
}

마지막은 선택적이기 때문에 지금 당장에는 필요한게 아닌것 같아 넣지 않았지만 참고~

  1. (Optional) Absolute imports
    Create a .babelrc file in the root of your project
{
  "presets": ["next/babel"],
  "plugins": [
    [
      "module-resolver",
      {
        "root": ["./"],
        "alias": {
          "@components": "./src/components",
          "@api": "./src/api",
          "@models": "./src/models",
          "@screens": "./src/screens",
          "@hooks": "./src/hooks",
          "@services": "./src/services",
          "@constants": "./src/constants",
          "@context": "./src/context",
          "@queries": "./src/queries",
          "@data": "./src/data",
          "@typeDefs": "./src/types",
          "@generated": "./src/generated",
          "@utils": "./src/utils",
          "@public": "./public"
        }
      }
    ]
  ]
}

material ui 설치하는 법 @
참고자료 :
https://dev.to/felixmohr/setting-up-a-blog-with-next-js-react-material-ui-and-typescript-2m6k

pages > _document.tsx 파일 만들어주고, fill it as follows..

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';
// import theme from '../src/theme';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <meta name="theme-color" />
          <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:300,400,500,700&display=swap" />
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Roboto+Slab:300,400,500,700&display=swap"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
    });

  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
  };
};

_document.ts is a file which is processed on server-side only.
What we are doing here is collecting the necessary CSS styles
generated by Material-UI and injecting them into the document as a string.
this way, we avoid any flickering when the client receives the page. if we were to skip the above step, the client would initially display the page which was rendered on the server and then inject its own styles, which could cause flickering.

_document.ts는 서버 측에서만 처리되는 파일이다. 여기서 우리가 하는일은 material-ui에서 생성된 필요한 css스타일을 모아서 문서에 문자열로 삽입하는것이다.
이렇게하면 클라이언트가 페이지를 수신할때 깜박임을 방지할 수 있다. 위 단계를 건너뛰면 클라이언트는 처음에서버에 렌더링된 페이지를 표시한 다음 자체 스타일을 삽입하여 깜빡임을 유발할수 있다.

  1. in your _app.tsx, apply a useEffect hook to remove the CSS that were injected on server-side from the client-side-app
    해당 _app.tsx에 useEffect를넣어준다.
import React, { useEffect } from 'react';
import Layout from '../components/Layout';
import '../styles/globals.css'
import { AppProps } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {

  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side')
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles)
    }
  }, [])

  return (
    <>
    <Layout>
      <Component {...pageProps} />
    </Layout>
    </>
  )
}
export default MyApp

By doing this, we allow the client to take over styling the app as soon as its ready.
이를 통해 앱이 준비되는 즉시 클라이언트가 즉시 스타일링을 맡아 처리할수 있게된다.

profile
on the move 👉🏼 https://sjeong82.tistory.com/

0개의 댓글