0. 파일구조
* TypeScript인 경우 1,2 과정 생략하고 tsconfig.json만 설정해도 됨!
1. babel-plugin-module-resolver 설치
babel-plugin-module-resolver는 Babel 플러그인으로,
모듈 경로를 재정의하거나 별칭(alias)을 설정하여 절대경로로 import 할 수 있게 한다.
- Babel
: ES2015 이상의 최신 명세의 문법을 구형 브라우저에서도 동작하는 코드로 트랜스파일해주는 개발 도구
: 개발 환경에서만 필요한 패키지 이므로 --save-dev 옵션이나 -dev 옵션을 추가하여 devDependencies에 설치한다.
npm 문서: https://www.npmjs.com/package/babel-plugin-module-resolver
npm install --save-dev babel-plugin-module-resolver
// or
yarn add --dev babel-plugin-module-resolver
2. babel.config.js에서 alias 설정하기
babel.config.js는 프로젝트 전체에 적용되는 설정 파일로서, 현재 작업 폴더를 루트로 지정한다.
보통 다음과 같은 구조로 되어있다.
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};
이러한 구조를 아래와 같이 변경한다
babel.config.js에서 alias 설정하면 Babel이 코드를 변환할 때 해당 경로를 올바르게 해석한다.
root 는 기준이 되는 위치이며, alias는 별칭으로 접근할 경로이다.
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
root:['.'],
extensions: [".ios.js", ".android.js", ".js", ".ts", ".tsx", ".json"],
alias: {
'@components': './src/components',
'@screens': './src/screens',
'@assets': './assets',
},
},
],
]
};
};
3. jsconfig.json 파일 생성하기 - Javascript
(TypeScript인 경우
tsconfig.json)
jsconfig.json 파일은 Visual Studio Code에서 모듈 경로를 해석하는 데 사용한다.
사용할 경로인 @components, @screens, @assets 들을 아래와 같이 추가한다.
baseUrl을 기준으로 각각의 폴더의 하위 모든 파일들을 @를 이용한 경로로 치환하는 설정이다.
이때 baseUrl과 babel.config.js에서 설정한 root와 동일해야 한다.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@screens/*": ["src/screens/*"],
"@assets/*": ["assets/*"],
},
},
"exclude": [
"node_modules",
"babel.config.js",
]
}
4. 적용 확인
경로 수정 후, 캐시 삭제하고 VSCode 재시작 후 다시 실행
npm cache verify
// or
yarn cache clean
참조
https://jw910911.tistory.com/116
React Native : 절대 경로 설정하기 (+ 타입스트립트)
React Native를 개발하다 보면 절대 경로 설정을 하고 싶을 때가 있습니다. 이때 헤메시는 분들을 위해 간단하게 정리해보겠습니다. 1. babel-plugin-module-resolver 설치하기 먼저 아래와 같은 babel-plugin-mod
jw910911.tistory.com
Expo 절대 경로 설정하기 (Path Alias)
왜 Path Alias 를 사용하나? import { PreviewType } from "../../../../../types/PreviewType"; IntelliJ 가 아니라면 대체 어느 폴더인지 알수가 없는 ../../ 이다 types 폴더가 다른 depth에 동일한 이름으로 존재한다면, 어
blog.yijunho.com
https://velog.io/@remon/React-Native-Babel-절대경로-세팅
[React Native] Babel 절대경로 세팅
React Native 와 Typescript 절대경로 설정하는 방법
velog.io
'Framework > React Native' 카테고리의 다른 글
[RN][Expo] Semi-Calories 개발 도움됐던 Document 정리 (0) | 2023.08.25 |
---|---|
[RN][Expo] Axios 를 이용해 API(Spring)와 통신 (0) | 2023.08.13 |
[RN][Expo] expo-media-library 앨범 사진 onEndReached로 계속 가져오기 (0) | 2023.08.01 |
[RN][Expo] expo-media-library 적용 (0) | 2023.08.01 |
[RN][Expo] expo-camera 적용 (0) | 2023.08.01 |