Hi, today I want to share about the absolute import for React and React-native projects.

When you create a project using create-react-app, it uses relative paths, which is fine for cases where the files you’re importing are relatively close within the file tree.

we import the file into react project, something like this:

It’s very difficult to count how many dots you required to import that file in our component.

But if there was a way to import the file the same way every time regardless of where the file in relation to another. This is where absolute import comes in handy. If you import above file something like this:    

No matter where you import those files from the path will be the same. No more counting dots.

Implementing Absolute Imports in Create-React-App:

Steps required to implement absolute imports when creating a react project using create-react-app command:

create-react-app is configured in such a way that its webpack configuration will automatically pick up ‘.env’ files and read the ‘NODE_PATH’ environment variable, which can then be used for absolute imports.

 

Hope this blog is useful for React and React-native developers.