DEV Community

Cover image for Alias in React Native
Suprabha
Suprabha

Posted on • Updated on

Alias in React Native

Creating Alias in React Native:

Is there anything more frustrating to find this path “../../../../../components/location” in Javascript?

What if we can use “/components/location” from any where in the code base?

Enter the Alias

So we are writing alias in .babelrc and we use a babel plugin to get aliasing set up, since we can’t use webpack in react native.

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

$ npm install babel-plugin-module-resolver
Enter fullscreen mode Exit fullscreen mode

Once we’ve installed, open up the project’s and find .babelrc file, If there is no .babelrc file then create the file .babelrc in root. Under the plugins key, add the below snippet:-

{
  "presets": ["react-native"],
  "plugins": [
    [
      "module-resolver",
      {
        "root": [
          "./src"
        ],
      "alias": {
         "src": "./src",
         "assets": "./src/assets"
       }
      } 
    ] 
  ]
}
Enter fullscreen mode Exit fullscreen mode

Now we can use “src/pages/homepage” instead of using complex relative paths like ‘../../../src/pages/homepage’

Now, clear the cache and restart the node server by following steps:

$ npm start --reset-cache

$ npm run ios
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this article ♥

I hope you would find the article useful. Feel free to ping me in comment section or @suprabhasupi 😋

🌟 Twitter 👩🏻‍💻 Suprabha.me 🌟 Instagram

Top comments (3)

Collapse
 
retyui profile image
Davyd NRB

Thanks for repeating documentation

reactnative.dev/docs/typescript#us...

Collapse
 
fyfirman profile image
Firmansyah Yanuar • Edited

in my project this is will not clear cache

npm start --reset-cache
Enter fullscreen mode Exit fullscreen mode

use this instead:

npm start -- --reset-cache
Enter fullscreen mode Exit fullscreen mode
Collapse
 
realabbas profile image
Ali Abbas • Edited

Good one! Thanks for sharing