노현진's Blog

React Native 프로젝트에 Path Alias 설정 방법

React Native 프로젝트에 Path Alias 설정 방법에 대해 정리한 페이지입니다.

Posted
Preview Image
By HyunJinNo

Tags

Mobile, React Native, TypeScript

Environment

OS: Windows 11

react v19.0.0

react-native v0.79.2

babel-plugin-module-resolver v5.0.2

1. 개요

React Native 프로젝트에 Path Alias 설정 방법에 대해 정리한 페이지입니다.

2. Step 1 - babel-plugin-module-resolver 패키지 설치하기

먼저 다음 명령어를 입력하여 babel-plugin-module-resolver 패키지를 설치합니다.

bash
1npm install --save-dev babel-plugin-module-resolver

3. Step 2 - babel.config.js 설정하기

다음과 같이 babel.config.js 파일을 열고 root에는 기준이 되는 폴더 경로를, alias에는 root와의 상대 경로를 지정합니다.

babel.config.js 설정

javascript
1module.exports = {
2  presets: ["module:@react-native/babel-preset"],
3  plugins: [
4    [
5      "module-resolver",
6      {
7        root: ["."],
8        alias: {
9          "@src": "./src",
10          "@assets": "./assets",
11        },
12      },
13    ],
14  ],
15};

4. Step 3 - tsconfig.json 설정하기

마지막으로 babel.config.js에서 지정한 경로를 tsconfig.json에도 작성합니다.

json
1{
2  "extends": "@react-native/typescript-config/tsconfig.json",
3  "compilerOptions": {
4    "skipLibCheck": true,
5    "baseUrl": ".",
6    "paths": {
7      "@src/*": ["./src/*"],
8      "@assets/*": ["./assets/*"]
9    }
10  }
11}

5. Step 4 - Path Alias 사용 예시

Path Alias 사용 예시는 다음과 같습니다.

5.1. src 폴더 예시

typescript
1import { NavigationContainer } from "@react-navigation/native";
2import { createNativeStackNavigator } from "@react-navigation/native-stack";
3import { RootStackParamList } from "./navigationTypes";
4import { HomeScreen } from "@src/pages/home";
5import { SettingScreen } from "@src/pages/setting";
6
7const Stack = createNativeStackNavigator<RootStackParamList>();
8
9export const Navigation = () => {
10  return (
11    <NavigationContainer>
12      <Stack.Navigator initialRouteName="Home">
13        <Stack.Screen name="Home" component={HomeScreen} />
14        <Stack.Screen name="Setting" children={SettingScreen} />
15      </Stack.Navigator>
16    </NavigationContainer>
17  );
18};

5.2. assets 폴더 예시

typescript
1import { BACKEND_URL } from "@env";
2import { useNavigation } from "@react-navigation/native";
3import { tw } from "@src/shared/lib/utils";
4import { Button, Image, Text, View } from "react-native";
5
6export const HomeScreen = () => {
7  const navigation = useNavigation();
8
9  return (
10    <View>
11      <Text>Home</Text>
12      <Text>{BACKEND_URL}</Text>
13      <Image
14        style={tw`aspect-2/3 h-96`}
15        source={require("@assets/background.jpg")}
16      />
17      <Button
18        title="설정화면으로"
19        onPress={() => navigation.navigate("Setting")}
20      />
21    </View>
22  );
23};

assets 폴더 예시

6. 참고 자료

© HyunJinNo. Some rights reserved.