Using Absolute Paths in React Native

abrahamlawson

Lawson

Posted on June 15, 2022

Using Absolute Paths in React Native

Expectation

// Hmmm
import {add} from '../../../../../../../utils';

// Awesome!
import {add} from 'utils';
Enter fullscreen mode Exit fullscreen mode

How ?

Step 1: Install babel-plugin-module-resolver

npm install --save-dev babel-plugin-module-resolver
// or
yarn add --dev babel-plugin-module-resolver
Enter fullscreen mode Exit fullscreen mode

Step 2: Add the following code to babel.config.js file.

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      require.resolve('babel-plugin-module-resolver'),
      {
        root: ["./src"],
      }
    ],
  ]
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Create file jsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": ["src/*"],
    }
  }
} 
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
abrahamlawson
Lawson

Posted on June 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related