coinpayu

    


    Most of the developers have frustrated about their messed file paths. When I start my new react native project, I wanted to set all prerequisites for clean code. 

Creating Alias in React Native:

    Initially, we need to install babel-plugin-module-resolver with yarn or npm.



    yarn add --dev babel-plugin-module-resolver

    # or if you use npm

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


Why do we need another babel plugin?

    This module resolver can simplify your code readability. You can easily import files and scaleup your projects faster.

Let's consider an example:


    import Module from '../../../Module' 


The above can be simplified into:


    import Module from 'components/Module' 
 
    // similarly 

    import Module from '@components/Module'


After installing plugin we need to update babel.config.js (you can also use .babelrc) and add 'module-resolver' to the list of babel plugins like following,


    
    module.exports = {
      presets: ['module:metro-react-native-babel-preset'],
      plugins: [
        [
          'module-resolver',
          {
            root: ['.'],
            extensions: [
              '.ios.ts',
              '.android.ts',
              '.ts',
              '.ios.tsx',
              '.android.tsx',
              '.tsx',
              '.jsx',
              '.js',
              '.json',
            ],
            alias: {
              '@app/theme': './app/theme',
              '@app/utils': './app/utils',
              '@app/redux': './app/redux',
              '@app/config': './app/config',
              '@app/assets': './app/assets',
              '@app/context': './app/context',
              '@app/screens': './app/screens',
              '@app/components': './app/components',
            },
          },
        ],
      ],
    };


  • Specify your root (Mostly app or src). This is not mandatory you can specify your own alias names like  '@component': './component'.

  • Use all your folders as clean structured way. So you can easily identify your roots.

Now you can directly import your files using alias as root instead of regular imports('../../../../Module'). Before run clear all your caches once.


If this really helpful to you please add your comments and support us.