Setting up aliases in React Native

폴더 구조

src
|
|--components
|----Avatar
|------index.tsx
|----Button
|------index.tsx
|
|--hooks
|----useFetch.ts
|----useTheme.ts
|
|--App.tsx

tsconfig.json 작성

tsconfig.json

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": ["src/*"],
      "@components": ["src/components/*"],
      "@hooks": ["src/hooks/*"]
    }
  }

babel-plugin-module-resolver 패키지 설치

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

babel.config.js or .babelrc

plugins: ['
'    //if you already have other plugin just paste this lines below
    [
        'module-resolver',
        {
          root: ['./src'],
          extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
          alias: {
						'@components': './src/components',
            '@hooks': './src/hooks/',
          },
        },
    ]
],

사용예시

import React from 'react';
import {
  View,
} from 'react-native';
import {useRemoteData} from 'hooks/useRemoteData'; //or '@hooks/useRemoteData'
import {Button} from 'components/button'; //or '@components/button'

const Home: React.FC = () => {
  return (
    <View >
      <Button />
    </View>
  );
};

export default Home;