DEV Community

Cover image for An Introduction to Absolute Imports in React Native
Anlisha Maharjan
Anlisha Maharjan

Posted on • Originally published at anlisha.com.np on

An Introduction to Absolute Imports in React Native

React Native Absolute imports — made easy for beginners.

Absolute imports help to simplify the paths and better organize the project as it grows. Also with absolute imports, it’s easier to copy-paste the code with imports into another file in the project and not have to tinker with import paths.

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

import Input from ‘../../../components/form/input’;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Or

$ yarn add --dev babel-plugin-module-resolver
Enter fullscreen mode Exit fullscreen mode

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 wants.

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 the 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 a custom base directory and we can import an input component located at src/components/form/input.js from like so:

import Input from '@app/components/form/input';
Enter fullscreen mode Exit fullscreen mode

Happy Learning! Feel free to give this article a clap and follow to stay up to date with more articles!

The post An Introduction to Absolute Imports in React Native first appeared on Anlisha Maharjan.

Top comments (0)