DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for React Native Absolute Imports Quick & Easy!
Anlisha Maharjan
Anlisha Maharjan

Posted on

React Native Absolute Imports Quick & Easy!

Absolute imports help to simplify the paths and better organize project as it grows. Also with absolute imports its easier to copy-paste the code with imports into another file in the project and not have to tinker with import paths. πŸ˜†

When project’s folder structure is complex, we are facing to have long relative imports in the project like this:

import Input from β€˜../../../components/form/input’;

It can be pretty hard to refactor and looks messy. The solution is to convert relative imports to absolute imports.

Step 1 β€” Install babel-plugin-module-resolver plugin

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

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

Step 2 β€” Update babel.config.js
Add the following code snippet in babel.config.js

module.exports = {
  plugins: [
    [
      'module-resolver',
      {
        alias: {
          '@app': './src',
        },
      },
    ],
  ],
}
Enter fullscreen mode Exit fullscreen mode

Note: @app is an alias one can give whatever one want.

Step 3 β€” Setup jsconfig.json or tsconfig.json

Using Javascript
Create/Open jsconfig.json file (in the root directory of the project) and add baseUrl and paths setting inside compilerOptions as shown in snippet below:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths" : {
      "@app/*": ["src/*"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Using TypeScript
If you’re using TypeScript in react native project, update tsconfig.json file (in the root directory of the project) and add the same setting inside compilerOptions as Javascript.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths" : {
      "@app/*": ["src/*"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4 β€” Implement Absolute Import
Absolute imports setting is now successfully configured with src folder as custom base directory and we can import a input component located at src/components/form/input.js from like so:

import Input from '@app/components/form/input';

That's it! Quick & Easy! Happy Learning!

Top comments (0)

πŸ‘€ Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.