DEV Community

Cover image for Absolute imports in React Native
Ian Felix
Ian Felix

Posted on

Absolute imports in React Native

This is a short guide on how to use absolute imports in React Native.

Absolute imports

The absolute imports are a feature that was introduced in ES2020. It allows you to import modules using an absolute path instead of a relative path.

For example, if you have a file called App.js in the src folder, you can import a module called utils.js using the following code:

import { sum } from 'src/utils';
Enter fullscreen mode Exit fullscreen mode

This is a simple example, but it can be very useful when you have a complex project with many files and folders.

How to use absolute imports in React Native

To use absolute imports in React Native, you need to install the babel-plugin-module-resolver package.

yarn add -D babel-plugin-module-resolver
Enter fullscreen mode Exit fullscreen mode

After installing the package, you need to configure it in the babel.config.js file.

module.exports = {
  presets: ['babel-preset-expo'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        alias: {
          '~/assets': './src/assets',
          '~/contexts': './src/contexts',
          '~/screens': './src/screens',
          '~/styles': './src/styles',
          '~/routes': './src/routes',
          '~/services': './src/services',
          '~/hooks': './src/hooks',
          '~/shared': './src/shared',
        },
      },
    ],
  ],
};
Enter fullscreen mode Exit fullscreen mode

The root property is used to define the root folder of the project. In this case, it is the src folder.

The alias property is used to define the aliases that will be used in the imports. In this case, I defined the following aliases:

  • ~/assets: ./src/assets
  • ~/contexts: ./src/contexts
  • ~/screens: ./src/screens

The aliases are used to import modules using the ~ character. For example, if you want to import the App.js file in the screens folder, you can use the following code:

import App from '~/screens/App';
Enter fullscreen mode Exit fullscreen mode

If you are using Typescript, you will need to add the following code to the tsconfig.json file:

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

It is important to note that the baseUrl property must be the same as the root property in the babel.config.js file.

Now you will be able to use absolute imports in your React Native project.

Thank you for reading this article.
If you enjoy this article, please upvote and comment.

Follow me on:

Top comments (3)

Collapse
 
jakub_jaboski_48ce8f7d8 profile image
Jakub Jabłoński

Hi, do you know what should i do more in my config to make it work?

babel.config.js:

module.exports = function(api) {
    api.cache(true);
    return {
        presets: [
            ['@babel/preset-env', {targets: {node: 'current'}}],
            'module:@react-native/babel-preset',
            '@babel/preset-typescript',
        ],
        plugins: [
            ['module-resolver', {
                root: ['./src'],
                alias: {
                    '@components': ['./src/components'],
                    '@screens': ['./src/screens'],
                    '@store': ['./src/store'],
                    '@utils': ['./src/utils'],
                    '@navigation': ['./src/navigation'],
                    '@hooks': ['./src/hooks'],
                    '@helpers': ['./src/helpers'],
                    '@core': ['./src/core'],
                    '@constants': ['./src/constants'],
                    '@config': ['./src/config'],
                    '@common': ['./src/common'],
                    '@api': ['./src/api'],
                    '@actions': ['./src/actions'],
                    '@providers': ['./src/providers'],
                    '@types': ['./src/types/types.d.ts'],
                    '@assets': ['./assets'],
                    '@common-types': ['./src/types/common-types.d.ts'],
                },
            }],
            ['module:react-native-dotenv', {
                moduleName: '@env',
                path: '.env',
                blacklist: null,
                whitelist: null,
                safe: true,
                allowUndefined: true,
            }],
            'react-native-reanimated/plugin',
        ],
    };
};
Enter fullscreen mode Exit fullscreen mode

and tsconfig.js

{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "sourceMap": true,
    "module": "ES2020",
    "noImplicitAny": false,
    "jsx": "react-native",
    "types" : ["react-native", "node"],
    "verbatimModuleSyntax": true,
    "strictNullChecks": true,
    "isolatedModules": true,
    "declaration": true,
    "noEmit": false,
    "allowJs": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "baseUrl": "./src",
    "paths": {
      "@components/*" : ["./components/*"],
      "@screens/*" : ["./screens/*"],
      "@store/*" : ["./store/*"],
      "@utils/*" : ["./utils/*"],
      "@navigation/*" : ["./navigation/*"],
      "@hooks/*" : ["./hooks/*"],
      "@helpers/*" : ["./helpers/*"],
      "@core/*" : ["./core/*"],
      "@constants/*" : ["./constants/*"],
      "@config/*" : ["./config/*"],
      "@common/*" : ["./common/*"],
      "@api/*" : ["./api/*"],
      "@actions/*" : ["./actions/*"],
      "@providers/*" : ["./providers/*"],
      "@types" : ["./types/types.d.ts"],
      "@assets/*" : ["../assets/*"],
      "@common-types": ["./types/common-types.d.ts"]
    }
  },
  "include": [
    "src/**/*",
    "numberExtenstions.d.ts"
    ]
}

Enter fullscreen mode Exit fullscreen mode

absolue paths for example import example from @Providers/example cant be resolved.

Collapse
 
jmquilario profile image
jmquilario

~/screens/Home could not be found within the project or in these directories:
didn't work in typescript

Collapse
 
ianfelix profile image
Ian Felix

Without code, I can't help you. Did you follow all the steps above?