Using path aliases with React Native

Path aliases in React Native

While your project scales you'll find yourself deep into the folder structure and looking at your imports from the deep down will be confusing. Plus let's face it, since IDE handles them for the most part it just looks bad as you scroll down from the top. Nevertheless it is a good practice to use aliases for your imports.

You can start with adding babel-plugin-module-resolver to your project.

yarn add -D babel-plugin-module-resolver

Adding typescript support is essential and pretty easy. Open your tsconfig.json file and add;

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

We are using @@ because some library names starts with single @ so babel gets confused if you use single @. But that being said you are not limited to use @@ sometimes I use ~ sometimes something completely different. So sky is the limit go nuts.

Last step would be letting babel know about what to replace so builds should work just fine. Open your babel.config.js and add fallowing to plugins;

    [
      'module-resolver',
      {
        alias: {
          '^@@(.+)': './src/\\1',
        },
        extensions: [
          '.ios.js',
          '.android.js',
          '.js',
          '.jsx',
          '.json',
          '.tsx',
          '.ts',
          '.native.js',
          '.png',
          '.jpg',
          '.svg',
        ],
      },
    ],

Your modules might be inside of a different folder. I put everything into src folder so I use ./src to let the babel and typescript know the location. Let's say your components, hooks, navigators etc. folders are inside of app/src you should change ./src with ./app/src so all the folders inside of that dictionary will be accessible with @@hooks, @@components etc.

Thats all you can add more extensions if you are using some other assets in your project but for the most part these should be just fine.