How to configure import alias in React Native
Tags: reactnative, tutorial, react
Published: 2021-05-27 15:20:01

---
title: How to configure import alias in React Native
published: true
date: 2021-05-25 00:00:00 UTC
tags: reactNative, tutorial, react
canonical_url: https://www.koprowski.it/blog/import-alias-in-react-native-and-vscode/
---

Import aliases are better for maintenance and more readable. Learn how to set up them in React Native!

Look at those two examples:
```js
1. import { InputArea } from '~components/InputArea'
2. import { InputArea } from '../../../../../components/InputArea'
```
We will learn how to set up our environment to have the first variant working.

## Aliases for `src` folder

For this tutorial, I assume that we have a standard React Native file structure. We want to create aliases to directories inside the `src` folder.

```bash{11-13}
├── App.js
├── __tests__
├── android
├── app.json
├── babel.config.js
├── index.js
├── ios
├── metro.config.js
├── node_modules
├── package.json
├── src
│   ├── components
│   └── helpers
└── yarn.lock

```

## Why is the tilde prefix `~` important?

The custom prefix is helpful when it comes to distinguishing your local imports from third-party packages. One look and you know which imports are from the project.

Here are two examples with the `helpers` folder:

```js
1. import something from 'helpers' // - without prefix
2. import something from '~helpers' // - with prefix
```

There is a package in the npm registry that is called `helpers`. If you decide to alias your `helpers` folder without any prefix then you risk a naming conflict.

I decided to stick with `~` as I haven't seen third party packages that use it. *There are other popular prefixes as well — my recommendation is sticking with tilde*

## Install Babel plugin

First of all, we have to add a proper plugin for the Babel compiler.

```bash
▶ yarn add --dev babel-plugin-module-resolver
```

## Adjust Babel config

Inside `babel.config.js` add `plugins` section. If it already exists, simply add `module-resolver` config like below. If you don't have this file. Then check for `.babelrc` or create one. All possible config files are listed [in the docs](https://babeljs.io/docs/en/config-files).

```js{9-14}
module.exports = {
	// ... some other config
  plugins: [
  	// ... some other plugins
    [
      'module-resolver',
      {
        root: ['./'],
        alias: {
          /**
           * Regular expression is used to match all files inside `./src` directory and map each `.src/folder/[..]` to `~folder/[..]` path
           */
          '^~(.+)': './src/\\1',
        },
        extensions: [
          '.ios.js',
          '.android.js',
          '.js',
          '.jsx',
          '.json',
          '.tsx',
          '.ts',
          '.native.js',
        ],
      },
    ],
  ],
};
```

Options are as described:

1. root - a string or an array of root directories,
2. alias - a map of aliases,
3. extensions - an array of file extensions used in the resolver.

### Regular expression as an alias

To prevent adding each `src` subfolder separately we want to use a regular expression for path completion. You can see the docs about using regular expressions on [babel-plugin-module-resolver Github page](https://github.com/tleunen/babel-plugin-module-resolver/blob/master/DOCS.md#regular-expressions).

### Restart metro process

The last step to make it work is restarting the _metro_ server. Simply use `ctrl + c` and then `yarn start` again in the terminal in your project.

If something is not working maybe you have to clear the cache - for that use `yarn start --reset-cache` command.

## How to make VSCode alias autocomplete working? 

With the config above code will compile and work as expected. Now we would like to have autocomplete work with our newly created aliases (or *IntelliSense* as named by Visual Studio Code creators).

We have to enter `jsconfig.json` file (or create it if it's not working).

```json{5}
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~*": ["src/*"]
    }
  },
  "exclude": ["node_modules"]
}
```

Inside `jsconfig.json` we have to specify two options: `baseUrl` and `paths` object. Here again, we are using a kind of regular expression to match all subdirectories in a single line.

### TypeScript support

What is interesting - in the TypeScript project I had to make a config a bit different to make it work:

```json{4}
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {"~*": ["./src/*"]}, 
  },
  "exclude": ["node_modules"]
}
```

Notice the dot before `src` path. I don't know why it required such a change. Maybe you have some idea? Let me know!

You can also check config in the [official docs for TypeScript aliases](https://reactnative.dev/docs/typescript#using-custom-path-aliases-with-typescript).

### Restart TypeScript process in VSCode

Autocomplete with new aliases should work immediately. If it is not maybe you have to restart TypeScript server (even for pure JS project as this server is responsible for autocompletion).

To do this open the command palette and type `Restart TS server`.

#### Thanks for reading

👉 [Check out latest React Native tips on my Twitter](twitter.com/Koprowski_it)

👉 [Stay updated about new tutorials on my Newsletter ✉️](https://koprowski.it/subscribe)