Using Absolute Paths in React Native

·

2 min read

In React Native, you can use absolute paths to import modules and files instead of relative paths. Absolute paths allow you to reference files and modules from any location in your project without specifying the relative path from the current file. This can make your code more readable and maintainable.

What do we want to achieve?

//  😏
import {TBCard} from '../../../../../components';

// 🙂 
import {TBCard} from '@components';

// and you can remove @ also and replace @ something you want

To set up absolute paths in React Native, you need to configure your project to support it. Here’s a step-by-step guide on how to do that:

  1. How?
npm install --save-dev babel-plugin-module-resolver
// or
yarn add --dev babel-plugin-module-resolver

// I am using babel-plugin-module-resolver version (5.0.0)

2. Create a jsconfig.json file in the root of your project.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "src/*": ["./src/*"],
      "assets/*": ["./src/assets/*"],
      "components/*": ["./src/components/*"],
      "constants/*": ["./src/constants/*"],
      "helpers/*": ["./src/helpers/*"],
      "hooks/*": ["./src/hooks/*"],
      "navigation/*": ["./src/navigation/*"],
      "redux/*": ["./src/redux/*"],
      "screens/*": ["./src/screens/*"],
      "theme/*": ["./src/theme/*"],
      "utils/*": ["./src/utils/*"],
    }
  }
}

The "baseUrl" option specifies the base directory for resolving absolute paths. In this example, we set it to ".", assuming your source code is located in the src directory. Adjust the value according to your project's structure.

3. Create a babel.config.js file in the root of your project.

module.exports = {
  plugins: [
    [
      'module-resolver',
      {
        alias: {
          src: './src',
          '@assets': './src/assets',
          '@components': './src/components',
          '@constants': './src/constants',
          '@helpers': './src/helpers',
          '@hooks': './src/hooks',
          '@models': './src/models',
          '@navigation': './src/navigation',
          '@redux': './src/redux',
          '@screens': './src/screens',
          '@services': './src/services',
          '@theme': './src/theme',
          '@utils': './src/utils',
        },
      },
    ],
  ],
};

4. Clean your cache

Please do not forgot to clear your cache and please restart metro bundler for ignore any error.It will works like charm!!

npx react-native start --reset-cache

5. Yo! It’s time to use

import {ScreensName} from '@constants/NavigationConstants';
import {HomeScreen, LandingScreen, TaskDetailsScreen} from '@screens';

By using absolute paths, you can import files and modules across your project more easily, regardless of the file’s location. It can simplify your import statements and help avoid confusion when dealing with complex file hierarchies.

Keep Coding!