[typescript] project 초기셋팅

chosh·2021년 11월 19일
0

1

yarn create react-app 프로젝트명 --template typescript

2

tsconfig.json 에 아래 내용 복사 붙여넣기

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "baseUrl": "./src",
    "allowJs": true,
    "noImplicitAny": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "outDir": "server/dist"
}

3

cd 프로젝트명

4

eslint 설치
yarn add -D eslint

5

yarn run eslint --init
To check syntax, find problems, and enforce code style
JavaScript modules (import/export)
React
Yes
Browser
Use a popular style guide
원하는 사이트 규칙 선택
JavaScript
Yes

yarn start 했을 때,
airbnb로 선택하고 이런 에러가 뜬다면 node 모듈 이런거 삭제 하지말고,

1. yarn add -D dotenv
2. root 폴더에 .env 파일 추가
3. .env에 SKIP_PREFLIGHT_CHECK=true 추가
4. gitignore 파일에 .env 추가(깃으로 관리 하지 않도록)
eslint 버전문제인데 추후 바뀔수 있음(안내문 따라 해보고 안되면 위의 방법대로)

6

yarn add -D eslint-config-airbnb 리액트 규칙 사용
yarn add -D eslint-config-airbnb-base 리액트 규칙 사용 x

7

yarn add -D eslint-plugin-prettier eslint-config-prettier
airbnb에서 제작한 리액트 관련 규칙을 설정해주는 플러그인을 설치

8

.eslintrc.js 에 붙여넣기

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'airbnb',
    'plugin:react/recommended',
    'plugin:jsx-a11y/recommended',
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint', 'prettier'],
  rules: {
    'linebreak-style': 0,
    'import/prefer-default-export': 0,
    'import/extensions': 0,
    'no-use-before-define': 0,
    'import/no-unresolved': 0,
    'react/react-in-jsx-scope': 0,
    'import/no-extraneous-dependencies': 0,
    'no-shadow': 0,
    'react/prop-types': 0,
    'react/jsx-filename-extension': [
      2,
      { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
    ],
    'jsx-a11y/no-noninteractive-element-interactions': 0,
    '@typescript-eslint/explicit-module-boundary-types': 0,
    '@typescript-eslint/no-unused-vars': ['error'],
    '@typescript-eslint/no-var-requires': 0,
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    },
  },
};

9

yarn add -D prettier

10

루프 폴더에
.prettierrc 파일 생성 및 아래 코드 붙여넣기

{
  "singleQuote": true,
  "semi": true,
  "useTabs": false,
  "tabWidth": 2,
  "trailingComma": "all",
  "printWidth": 80,
  "arrowParens": "always",
  "orderedImports": true,
  "bracketSpacing": true,
  "jsxBracketSameLine": false
}

11

yarn add -D styled-reset

12

src폴더 안에 assets 폴더를 만들고, 그 안에 styles 폴더를 만들고, 그 안에
globalStyle.ts 파일 생성
styled.d.ts 파일 생성
theme.ts 파일 생성

globalStyle.ts

import { createGlobalStyle } from 'styled-components';
import { normalize } from 'styled-normalize';
import reset from 'styled-reset';

const GlobalStyle = createGlobalStyle`
  ${reset}
  ${normalize}
  html,
  body {
    overflow: hidden;
  }
  * {
    box-sizing: border-box;
  }
`;

export default GlobalStyle;

styled.d.ts

import 'styled-components';

declare module 'styled-components' {
  export interface DefaultTheme {
    basicWidth: string;
    color: {
      purple: string;
      violet: string;
      skyblue: string;
      mint: string;
      black: string;
      darkGray: string;
      gray: string;
      paleBlue: string;
      paleBlue: string;
      stone: string;
      white: string;
      yellow: string;
      red: string;
      green: string;
      blue: string;
    };
  }
}

theme.ts

import { DefaultTheme } from 'styled-components';

const theme: DefaultTheme = {
  basicWidth: '320px',
  color: {
    purple: '#5D4EE8',
    violet: '#A29DFC',
    skyblue: '#6AB4F7',
    mint: '#50E2BF',
    black: '#1c0201',
    darkGray: '#3D4044',
    gray: '#77828B',
    paleBlue: '#BECBD8',
    stone: '#EEEEEE',
    white: '#FFFFFF',
    yellow: '#F4AE3D',
    red: '#ee4f41',
    green: '#42a621',
    blue: '#305fee',
  },
};
export { theme };

13

src 안에
pages 폴더 생성
components 폴더 생성

pages 안에 기본 페이지 파일 생성
ex) src/pages/Home/Home.tsx

Home.tsx

import React from 'react';

const Home = function () {
  return <div>기본파일 생성</div>;
};

export default Home;

14

yarn add -D react-router-dom @types/react-router-dom

15

src 폴더 아래
RouterFile.tsx 생성 (파일 이름 맘대로 생성)

react-router-dom 버전이 6이상일때,
RouterFile.tsx

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from 'pages/Home/Home';

const RouterFile = function () {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
      </Routes>
    </BrowserRouter>
  );
};

export default RouterFile;

react-router-dom 버전이 6이하일때,
Routes.tsx

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Home from 'pages/Home/Home';

const Routes = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
      </Switch>
    </BrowserRouter>
  );
};

export default Routes;

6버전부터 달라졌습니다
https://reacttraining.com/blog/react-router-v6-pre/

16

yarn add -D styled-components @types/styled-components styled-normalize

17

eslint 가 적용되지 않고 error 가 뜬다면 vscode 재부팅

18

아래의 에러가 뜬다면

Error while loading rule 'prettier/prettier': context.getPhysicalFilename is not a function
Occurred while linting

이분 블로그 참조
https://velog.io/@qhgus/React-ESLint-prettier-%EC%84%B8%ED%8C%85-%ED%9B%84-%EC%97%90%EB%9F%ACcontext.getPhysicalFilename-is-not-a-function

profile
제가 참고하기 위해 만든 블로그라 글을 편하게 작성했습니다. 틀린거 있다면 댓글 부탁드립니다.

0개의 댓글