gincheong / Memo

개발 관련 내용들을 메모하기 위한 용도로 만든 빈 레포지토리입니다.
0 stars 0 forks source link

craco를 사용하여 CRA의 tsconfig에서 alias 사용하기 #41

Open gincheong opened 3 years ago

gincheong commented 3 years ago

jscoonfig.json도 덮어썼었나? 그건 잘 기억이 왜 안 날까


tsconfig.json에 alias 설정을 모두 마치고 나서, react-scripts start 를 실행하면, react-scripts가 tsconfig 파일의 내용물을 수정한다.

alias 관련 설정을 다 지운다거나, noEmit: true 설정을 하여 컴파일하고 결과 파일이 아무것도 안 나오게 한다거나..

noEmit 속성의 경우에는 번거롭기는 해도 컴파일한 결과물이 필요할 때만 직접 수정하면 되지만,

alias 설정의 경우에는 tsconfig에서 아예 삭제가 된 후에 프로젝트가 실행되기 때문에 오류가 발생한다.

gincheong commented 3 years ago
npm install @craco/craco
npm install craco-alias

craco를 설치하고, 루트 경로에 alias 정보를 저장할 tsconfig.paths.json 파일을 생성하자

// tsconfig.paths.json
{
  "compilerOptions": {
    "paths":{
      "@components": ["./src/components"],
      "@context": ["./src/context"],
      "@shared": ["./src/shared"],
      "@shared/models": ["./src/shared/models"],
      "@utils": ["./src/utils"],
      "@assets": ["./src/assets"]
    }
  }
}

그리고 tsconfig.json에 이 파일을 extends로 추가해 준다

// tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  ...
}
gincheong commented 3 years ago

마지막으로 craco.config.js 파일을 생성하자.

// craco.config.js
const CracoAlias = require('craco-alias');

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: 'tsconfig',
        // as you know, CRA doesn't allow to modify tsconfig's compilerOptions
        // so you should create a separate JSON file and extend tsconfig.json from it
        // and then just specify its path here:
        tsConfigPath: 'tsconfig.paths.json',
      },
    },
  ],
};
gincheong commented 3 years ago

마지막으로 npm scripts에서, react-scripts 명령어를 craco로 바꾸면 된다

{
  "scripts": {
    "start": "craco start",
    "test": "craco test",
    "eject": "react-scripts eject"
  }
}

eject는 여전히 react-scripts로 실행해야 함을 유의하자

이렇게 하면 npm run start 할 때, alias가 적용된 상태로 프로젝트를 실행할 수 있다

gincheong commented 2 years ago

https://velog.io/@shin6403/React-Typescript-%EC%A0%88%EB%8C%80%EA%B2%BD%EB%A1%9C-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0feat.React-CRA

위처럼 하면 일괄 alias 적용이 가능하다