How to add path alias in React Native and to configure editors

Isn’t it frustrating to locate a file by path, for example by “../../../../../path/to/component” in import or require calls. Is there a better way for example making it like @core/component or @src/component? Yes, there is.

Using path alias in React Native

There is a plugin named babel-plugin-module-resolver which works exactly the way as the name suggests. All you need to do is to install and configure it correctly.

npm install --save-dev babel-plugin-module-resolver

or using Yarn

yarn add --dev babel-plugin-module-resolver

Once installed add this code to .babel.rc but before that check the note below.

Note: In your react native project make sure about the configuration file in use. It might be module specific .babelrc or app-wide babel.config.js. We use .babel.rc here in this example. You can know more about the difference here.

Okay so we add the following code to our configuration file babel.rc

{
  "plugins": [
    ["module-resolver", {
      "@src": ["./src"],
      "alias": {
        "@test": "./test"
      }
    }]
  ]
}

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

$ npm start --reset-cache
$ npm run ios

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

Configure path alias in React for VSCode editor

Configure the path mapping in jsconfig.json (tsconfig.json for TypeScript), e.g.:

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

you can check Editors autocompletion section of module home page here.

Conclusion

A path alias or shortcut can be added to a React or React Project application with help of “babel-plugin-module-resolver” package. After installing configure your aliases in the .babel.rc or relevant configuration file of your project. You can also configure your code editor to listen to the path changes in your code base.

Leave a Reply