Reduce Long Import Statements in React Native with Absolute Imports

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 4 years ago

In large React Native projects, it’s common to have long relative import paths like:

import MyComponent from '../../../screens/MyScreen/MyComponent'

With import paths that go up and down the folder hierarchy like that, it can be confusing to figure out which file or folder you’re actually importing, and it generally just looks messy to have several of those import statements at the top of your file.

Instead, we can convert relative import paths to absolute import paths by creating a new package.json file at any level of the folder hierarchy. That package.json file needs to specify a name that you want to call that folder:

{ "name": "screens" }

And then you can begin your import statements with that new module name:

import MyComponent from 'screens/MyScreen/MyComponent'

Note that this only works for React Native projects, and not other npm based projects like create-react-app web apps.

Instructor: [00:00] To turn relative import statements into absolute import statements, we can reference the project name just like any npm module. In the package.json file in the root of the project, locate and copy the name of the react-native project. Then, in your component, you can refer to that name as the root of the import path.

[00:20] We can now go from the project group, to source, images, and into shapes. When we rerun that, the images still load. Now, we have a nice absolute import path.

[00:34] We still have to list the project name multiple times, however, but we can clean that up further by adding a new package.json file, which allows us to reference a new level of the folder hierarchy as the absolute import.

[00:47] Make a new package.json file in the source folder. That package file only needs to specify one thing, which is the name of the new package. That's how we would refer to the folder while importing.

[00:59] Now, we can reference that source folder as the root of the import path, and everything still loads. We can add a package.json file to any level of the folder tree that we want. Let's add a new one to images and call that new package "Images."

[01:17] Now, we can change all of our imports to reference images directly, which significantly cleans up the import statements.