Improving your React Native code using Path Aliases

Luiz Gabriel - Mar 1 '23 - - Dev Community

When we develop an application with many folders the import paths are often too large and this affects the readability of your code as per the example below:

import Input from '../../../src/components/Input';
import HomeSvg from '../../../src/assets/home.svg';
Enter fullscreen mode Exit fullscreen mode

To solve this problem we will have to make some settings:

1º Step: Libs Install

  • Install metro-react-native-babel-preset and babel-plugin-module-resolver as devDependencies
npm install metro-react-native-babel-preset --save-dev
yarn add metro-react-native-babel-preset -D
Enter fullscreen mode Exit fullscreen mode
npm install babel-plugin-module-resolver --save-dev
yarn add babel-plugin-module-resolver -D
Enter fullscreen mode Exit fullscreen mode

2º Step: Babel Configuration

  • alias: In will have the paths and the name that will be used when calling the specified path.

  • extensions: Extensions to the files that will be used

module.exports = function(api) {
  api.cache(true);
   return {
     presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset'],
     plugins: [
       "module-resolver",
       {
         alias: {
           // This needs to be mirroned in tsconfig.json/jsconfig.json
          components: "./src/components",
          svg: "./src/assets",
         },
         extensions: ['.js', '.jsx', '.tsx'],
       },
     ],
   };
};
Enter fullscreen mode Exit fullscreen mode

3º Step: tsconfig/jsconfig configuration

  • Access the tsconfig.json or jsconfig.json file

  • If neither of these files exist, create them in the project root

  • paths: Add the same paths added in babel.config.js, if the called folder does not have an index calling all files it is necessary to put "/*"

  • baseUrl: Tell the typescript where to start importing

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      // This needs to be mirrored in babel.config.js
      "components": ["./src/components"],
      "svg/*": ["src/assets/*"],
    }
  },
  "extends": "expo/tsconfig.base"
}
Enter fullscreen mode Exit fullscreen mode

Final Result

import Input from 'components/Input';
import HomeSvg from 'svg/home.svg';
Enter fullscreen mode Exit fullscreen mode
. . . . .