Alias in React Native

Suprabha - Jun 3 '20 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player