개발 초기 세팅

broccoli·2021년 7월 29일
0

초기세팅

목록 보기
1/1
post-thumbnail

개발을 진행하기 앞서 항상 프로젝트마다 세팅을 해두도록 하자.

1. npm 패키지 설치

npm i -D eslint prettier eslint-plugin-prettier

eslint와 prettier인데, 전역으로 피씨에 설치가 되어 있을 수 있지만 프로젝트마다 다른 설정이 가미될 필요가 있기 때문에 이렇게 프로젝트별로 따로따로 세팅을 하는게 좋다.

  • eslint : 코드 품질 검사
  • prettier: 코드 정렬 도구
  • eslint-plugin-prettier : eslint 와 prettier를 연결해주는 도구

2. eslint 세팅 설치

npx eslint --init

이수 .eslintrc에 가서 prettier가 포맷팅 해주는 것을 기본으로 하는 것으로 한다.

...
  extends: ['plugin:prettier/recommended'],
...
module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: ['plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint'],
  rules: {},
}

3. prettier 설정 세팅

.prettierrc 파일 만든다.

{
  "semi": false,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 120, // NEW LINE을 해주는 폭. 짧게하면 의도치않게 뉴라인될 수 있음. 
  "tabWidth": 2,
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "useTabs": false
}

4. ts

타입스크립트는 앞으로도 점점점점점점점 무조건 쓰게 되는 언어이므로 꼭 익혀두는게 좋다.

// tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,
    "target": "ES5", //변환 타겟은 es5로 한다.
    "outDir": "./dist", //  compiled output path
    "esModuleInterop": true, // import * as React from 'react' 이것을 as로 안붙이고 바뀔수 있도록 해줌.
    "sourceMap": true,
    "noImplicitAny": true
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "jsx": "react", // jsx라는 확장자는 react거라는것 명시
    "module": "esnext", //모듈은 최신 import export 사용한다는것
    "moduleResolution": "Node", // node가 import export를 해석하게 해준다.
    "strict": true, //엄격하게 체크하겠다.
    "resolveJsonModule": true, //import json파일 허락한다.
    "baseUrl": ".",
    // ../../ 이런 상대경로의 패스를 지정해준다. 타입스크립트가 검사하는 경로
    "paths": {
      "@폴더명/*": ["폴더명/*"],
	"typeRoots": ["./node_modules/@types", "./types"]// 디폴트로 노드모듈안에 @types를 바라본다. 추가로 커스텀 타입을 해야하는 패키지를 사용지 정의한 폴더를 추가하면 된다.
    },
    "include": ["./src/**/*"], //포함경로 : 디폴트가 따로 있음
    "exclude": ["node_modules", "dist", "built"] //제외경로: 디폴트가 따로 있음
  }
}

예를 들어 chart.js라는 패키지가 타입정의된 패키지가 없을때 tsconfig에 위와 같이 typeRoots를 추가해주고 프로젝트루트에 types은 같은 임의에 폴더를 만들어 타입들을 정의해준다.

ex) types/chart.js/index.d.ts

//index.d.ts
declare module 'chart.js' {
  interface MyChart {}
}

4-1. 세팅방법

리액트를 사용한다 가정하고 리액트 관련 패키지도 해줌.

npm i typscript
#리액트관련 패키지
npm i @types/react @type/react-dom react react-dom

4-2. vscode 세팅추가

{
  "editor.tabSize": 2,
  "editor.wordWrap": "on",
  "html.format.wrapLineLength": 0,
  "editor.formatOnPaste": true,
  "todohighlight.isEnable": true,
  "stylelint.enable": true,
  "workbench.startupEditor": "newUntitledFile",
  "[markdown]": {
    "editor.wordWrap": "on",
    "editor.quickSuggestions": true,
    "editor.formatOnSave": false,
    "editor.tabSize": 2,
    "editor.formatOnPaste": false
  },
  "[json]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnPaste": false,
    "editor.quickSuggestions": true,
    "editor.wordWrap": "on",
  },
  "[javascript]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
  },
  "[html]": {
    "editor.wordWrap": "on",
    "editor.quickSuggestions": true,
    "editor.formatOnSave": true,
    "editor.tabSize": 2,
    "editor.formatOnPaste": true
  },
  "emmet.includeLanguages": {
    "javascript": "javascriptreact",
    "editor.formatOnSave": "true"
  },
  "[css]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
  },
  "[javascriptreact]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
  },
  "[typescript]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
  },
  "[typescriptreact]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
  },
  "javascript.updateImportsOnFileMove.enabled": "always",
  "files.exclude": {
    "**/node_modules": true
  },
  "html.format.enable": false,
  "liveServer.settings.donotShowInfoMsg": true,
  "files.associations": {
    ".tsconfig.json": "jsonc"
  },
  "eslint.alwaysShowStatus": true,
  // 이게 있어야지 vscode에서 프로젝트의 .eslintrc.js를 잘 캐치한다.
  "eslint.workingDirectories": [
  {"mode": "auto"}
  ],
}

5. 바벨

바벨은 6to5라는 명칭으로 불렸었는데 이것은 es6를 es5로 변경해준다는 의미이다. 브라우저가 일반적으로 적용하던 자바스크립트파일이 es5만이었을 때 브라우저가 인식하는 자바스크립트의 모습으로 변경해준다는 의미이다. 지금은 브라우저가 최신 자바스크립트 소스를 많이 받아주지만 브라우저마다 조금씩 다를 수 있기 때문에 한번 바벨로 적용해주는것이 좋다.

바벨은 이미지와 css까지 자바스크립트로 변경해준다.
이건 웹팩이랑 쎄뚜쎄뚜로 쓰는 경우가 많으므로 설치 세팅은 아래에 웹팩과 같이 보면 된다.

6. webpack.config.ts

타입스크립트를 쓸때는 웹팩 4로 하는게 좋다. 아직 webpack 5로 호환안되는 패키지 많음

혹시 아래 세팅을 모두 설치했는데도 webpack.config.ts가 로드되지 않는다면 해당 파일에 참조하고 있는 패키지가 설치되지 않은게 있는지 확인하고 설치하고 다시 진행하면 된다. 에러메세지를 잘 확인해봐라~

6-1. 설치

리액트를 사용하는 경우는 @babel/preset-react도 추가한다.

npm i webpack webpack-cli @babel/core babel-loader @babel/preset-env -D
# 리액트를 위해 추가
npm i @babel/preset-react -D
# 타입스크립트를 위해 추가
npm i @types/webpack @types/node @babel/preset-typescript ts-node  -D
# 스타일을 위해 로더 설치
npm i css-loader mini-css-extract-plugin @types/mini-css-extract-plugin css-minimizer-webpack-plugin @types/css-minimizer-webpack-plugin -D
# hot reload
npm i @types/webpack-dev-server @types/webpack-dev-server -D
# html 따로 생성해주기
npm i -D html-webpack-plugin

참고로 ts를 사용할 때 웹팩데브서버를 실행하는 스크립트는 아래와 같이 해줘야한다.

// package.json
...
"dev": "TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack serve --env=development"
...

6-2. 타입스크립트로 인해 추가로 해줘야 할 것

tsconfig-for-webpack-config.json을 만든다.
안에 아래 이부분을 넣는다.

웹팩공식문서에 가면 나온다.

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "Node",
    "target": "es5",
    "esModuleInterop": true
  }
}

웹팩은 번들러도구인데, 여러개가 있지만 웹팩이 대세이고 쓰는 방법을 이해한다면 가장 편리하고 레퍼런스가 많기 때문에 번들러는 요거 하나만 알면 된다. 세팅을 일반적으로 비슷하기에 잘만든 세팅 재사용하자.

6-3. 웹팩데브서버

// bash

아래 예는 ts를 기준으로 하고 있고 js를 기준으로 한다면 타입설정을 제외해주면된다.

import path from 'path'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin'
import webpack from 'webpack'

const isDevelopment = process.env.NODE_ENV !== 'production'

const config = {
  name: 'slack-clone',
  devtool: isDevelopment ? 'eval-source-map' : 'hidden-source-map',
  mode: 'development',
  resolve: {
    extensions: ['.jsx', '.js', '.tsx', '.ts'],
  },
  entry: {
    app: ['./src/app.tsx'],
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, 'dist'),
    clean: true,
    publicPath: '/',
  },
  plugins: [
    new MiniCssExtractPlugin(),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src/index.html'),
    }),
    new webpack.EnvironmentPlugin({ NODE_ENV: isDevelopment ? 'development' : 'production' }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.tsx?$/i,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              [
                '@babel/preset-env',
                {
                  targets: {
                    browsers: ['> 1% in KR'],
                  },
                  debug: isDevelopment,
                },
              ],
              '@babel/preset-react',
              '@babel/preset-typescript',
            ],
            plugins: ['@babel/plugin-transform-runtime'],
            env: {
              development: {
                plugins: [['@emotion', { sourceMap: true }]],
              },
              production: {
                plugins: ['@emotion'],
              },
            },
          },
        },
      },
      {
        test: /\.jsx?$/i,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              [
                '@babel/preset-env',
                {
                  targets: {
                    browsers: ['> 1% in KR'],
                  },
                  debug: isDevelopment,
                },
              ],
              '@babel/preset-react',
            ],
            plugins: ['@babel/plugin-transform-runtime'],
          },
        },
      },
    ],
  },
  optimization: {
    minimizer: [new CssMinimizerPlugin()],
  },
  devServer: {
    port: 3020,
    contentBase: path.resolve(__dirname, 'dist'),
    historyApiFallback: { index: '/', disableDotRule: true },
    publicPath: '/',
  },
}

export default config

6-4. tsconfig-for-webpack-config.json

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "Node",
    "target": "es5",
    "esModuleInterop": true
  }
}

99. etc

만약 eslint 룰을 제외하고 싶은 폴더가 있다면 세팅에 아래와 같이 설정을 추가한다.

// .eslintrc.js
...
eslintIgnore: ['./dist/**/*.js', '/node_modules/**', './*.json'],
...

ℹ️ 만약 json파일에 주석을 치는것에 자꾸 빨간 경고가 뜬다면 vscode기준 다음과 같은 설정을 추가해준다.
vscode user 설정환경 파일
vscode 우측하단에 JSON버튼을 클릭해서 JSON WITH COMMENTS라는 것을 선택하면 아래 설정이 자동 등록된다.

// settings.json
  "files.associations": {
    ".tsconfig.json": "jsonc"
  },
profile
🌃브로콜리한 개발자🌟

0개의 댓글