typescript paths 관련 문제 3가지와 해결책

Dave Lee·2022년 1월 7일
5

typescript로 nodejs나 react 프로젝트를 진행할 때 paths를 설정하면 경로를 깔끔하게 관리할 수 있다.
가령

import dummy from '../../constants';

이런 경로를

import dummy from '@constants';

이렇게 사용할 수 있는 것이다.

그런데 사용하다보면 이런저런 문제가 발생한다. 이 중 찾는데 시간이 좀 걸렸던 문제들을 정리한다.

cra에서 paths 설정시 초기화 문제

typescript의 paths는 기본적으로는 tsconfig.json에서 다음과 같이 할 수 있다.

{
    "compilerOptions": {
        :
      	:
        "baseUrl": "./",
        "paths": {
            "@constants/*": ["src/constants/*"],
			"@routers/*": ["src/routers/*"],
            "@controllers/*": ["src/controllers/*"],
            "@services/*": ["src/services/*"],
        }         
    }
}

그런데 create-react-app (typescript template)로 생성한 경우 tsconfig의 path부분이 초기화 되는 문제가 있을 수 있다. 이 때는 paths부분을 tsconfig.paths.json에 별도로 작성한 다음

tsconfig.json

{
	"extends": "./tsconfig.paths.json",
}

craco를 쓴다면 craco.config.js

/* eslint-disable @typescript-eslint/no-var-requires */
const CracoAlias = require('craco-alias');

module.exports = {
  :
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: 'tsconfig',
        baseUrl: '.',
        tsConfigPath: 'tsconfig.paths.json',
        debug: false,
      },
    },
  ],
};

이렇게 설정해주자.

paths 설정후 폴더명 import시 index.ts를 읽지 못하는 문제

paths 설정시 보통 * 를 써서 하위 모든 파일에 대응하는데 이것이 폴더명 그자체를 include할 때는 작동하지 않았다.

import Config from '@config';

오류 : Cannot find module '@config' or its corresponding type declarations.ts(2307)

이 때는 * 없는 문장을 한문장씩 더 써주어서 해결할 수 있다.

 "paths": {
            "@config": ["src/config"],
            "@config/*": ["src/config/*"],
  }

paths에서 @types include 문제

"@types/*": ["src/types/*"],

이렇게 쓴 후 type 정의를 다음과 같이 하려고 하면 오류가 난다.

import type Blabla from '@types/Bla';

다른 모든 폴더는 다 되는데 이 @types만 작동하지 않는다. 이는 @types가 예약어처럼 다른경로(아마도 node_modules)를 찾기 때문인것 같다. 분위기를 깨지 않는 우회 방법은

"@@types/*": ["src/types/*"],

이렇게 골뱅이를 두개 붙여주는 것이다.

profile
developer

0개의 댓글