숨참고 개발다이브

[React Native] tsconfig.json baseUrl 설정과 Unable to resolve module 에러 해결 본문

개발/React & React Native

[React Native] tsconfig.json baseUrl 설정과 Unable to resolve module 에러 해결

사라 Sarah 2024. 2. 22. 18:46
728x90

Typescript baseUrl 설정

 

기존에 컴포넌트 혹은 파일을 import 할 때 경로가 깊어질수록 상대경로가 길어지는 문제가 있다.

 

import { SvgImageExample } from '../../assets/svgs';

 

하지만 tsconfig.json의 baseUrl 속성을 사용해 절대경로를 지정하면 ‘../../’ 부분이 생략이 가능해진다.

나는 프로젝트 Root 하위에 src라는 폴더에서 코드를 관리하기 때문에 절대경로를 ‘./src’로 지정해 주었다.

 

{
  "compilerOptions": {
    "baseUrl": "./src",
  }
}

 

해당 속성을 지정해 주면 import 경로를 다음과 같이 가독성 좋게 변경할 수 있다.

 


 

Unable to resolve module 에러 해결

 

하지만 해당 속성을 설정한 후 프로젝트를 실행하면 다음과 같은 오류가 발생하게 되었다.

 

Error: Unable to resolve module assets/svgs from ...

 

이를 해결하기 위해 다음과 같은 설정을 진행해 주었다. 해당 프로젝트에서는 eslint도 사용하기 때문에 eslint 관련 설정도 포함해 주었다.

 

1. 터미널에서 다음 코드 실행

 

yarn add babel-plugin-module-resolver eslint-import-resolver-babel-module eslint-plugin-import

 

  • babel-plugin-module-resolver: Babel 플러그인 중 하나로, 모듈을 해석하고 해석된 모듈 경로에 대한 별칭(alias)을 지정할 수 있도록 도와줌
  • eslint-import-resolver-babel-module: ESLint 플러그인 중 하나로, ESLint에서 import 문을 해석하고 해석된 모듈 경로에 대한 별칭을 지정할 수 있도록 도와줌
  • eslint-plugin-import: ESLint 플러그인 중 하나로, import 문과 관련된 여러 가지 규칙을 제공합니다. 이를 통해 코드의 가독성과 품질을 향상시키고 모듈을 올바르게 사용하는지 검사할 수 있다.

 

2. babel.config.js 및 .eslintrc 파일에서 다음 속성을 추가

// babel.config.js

...
plugins: [
    [
      'module-resolver',
      {
        cwd: 'babelrc',
        root: ['./src'],
        extensions: [
          '.ios.ts',
          '.android.ts',
          '.ts',
          '.ios.tsx',
          '.android.tsx',
          '.tsx',
          '.jsx',
          '.js',
          '.json',
        ],
      },
    ],
  ],
...

 

// .eslintrc
...
  "settings": {
    "import/resolver": {
      "babel-module": {}
    }
  }

 

 

728x90

 

 

tsconfig.json의 options

tsconfig.json의 더 많은 옵션 항목들은 공식 홈페이지에서 확인 가능하다.

https://www.typescriptlang.org/tsconfig

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org

 

 

 

300x250
Comments