- 공식 깃헙 : babel-plugin-module-resolver
- 참고 블로그 : https://aleksefo.medium.com/how-to-setup-module-resolution-and-path-aliases-with-react-native-and-typescript-f4924669780a ← 추천!
1) module-resolver 설정
설치
$ yarn add --dev babel-plugin-module-resolver or $ npm install --save-dev babel-plugin-module-resolver
설정
프로젝트루트경로/babel.config.js
/* eslint-disable no-dupe-keys */ const pathPlugin = [ [ 'module-resolver', { root: ['./'], extensions: [ '.ios.ts', '.android.ts', '.ts', '.ios.tsx', '.android.tsx', '.tsx', '.jsx', '.js', '.json', ], alias: { '*': './src', '@components': './src/components', '@navigators': './src/navigators', '@screens': './src/screens', '@assets': './src/assets', '@lib': './src/lib', '@recoil': './src/recoil', '@storage': './src/storage', }, }, ], ]; module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [...pathPlugin], };
2) VSCode 자동완성 연동
- VSCode jsconfig 공식문서 : https://code.visualstudio.com/docs/languages/jsconfig
- babel-plugin-module-resolver 공식 문서 : https://github.com/tleunen/babel-plugin-module-resolver#editors-autocompletion
자바스크립트 프로젝트 : 프로젝트루트경로/jsconfig.json
타입스크립트 프로젝트 : 프로젝트루트경로/tsconfig.json
jsconfig.json으로 해도 되는데, 사실
jsconfig.json
은 tsconfig.json
에 "allowJS": true
속성이 추가된 것일 뿐이므로, 타입스크립트 전환까지 생각해서 그냥 tsconfig.json으로 만들었음.{ "compilerOptions": { "baseUrl": ".", "paths": { "*": ["./src/*"], "@components/*": ["./src/components/*"], "@navigators/*": ["./src/navigators/*"], "@screens/*": ["./src/screens/*"], "@assets/*": ["./src/assets/*"], "@lib/*": ["./src/lib/*"], "@recoil/*": ["./src/recoil/*"], "@storage/*": ["./src/storage/*"] }, "allowJs": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "isolatedModules": true, "jsx": "react", "lib": ["es6"], "moduleResolution": "node", "noEmit": true, "strict": true, "target": "esnext" }, "exclude": [ "node_modules", "babel.config.js", "metro.config.js", "jest.config.js" ] }
JS프로젝트에서 tsconfig.json을 사용할 때 발생할 수 있는 이슈
react와 react-native를 임포트할 때 아래와 같은 워닝이 뜨면서 해당 모듈과 관련된 자동완성이 안뜰 수 있다.
Quick Fix해서 타입들을 설치하면 해결되나, 자바스크립트로만 작업을 하고있다면 그냥 jsconfig.json으로 작성하는 것도 방법이다.

3) 트러블 슈팅
yarn start --reset-cache
제대로 설정했음에도 잘 동작하지 않는다면, 예전의 캐시로 파일 경로를 resolve하는 것이 원인일 수 있다.
캐시를 날리고 다시 실행시켜보면 웬만하면 잘 된다.
watchman watch-del-all && rm yarn.lock && rm -rf node_modules && rm -rf $TMPDIR/metro-* && rm -rf $TMPDIR/haste-map-* && yarn && yarn start --reset-cache
watchman watch-del '/Users/haneojin/Desktop/algocare-device-app' ; watchman watch-project '/Users/haneojin/Desktop/algocare-device-app’
캐시 날리는 것으로 해결이 안될 때의 해결방법이다.
tsconfig.json
babel.config.json
설정파일의 설정도 제대로 했고,
babel-plugin-module-resolver
모듈 설치도 제대로 됐다면 위의 명령어로 다 해결될 것이다.