React tips — Working with relative path using create-react-app

Leonardo Bruno Lima
4 min readAug 3, 2018

--

Photo by Jack Anstey on Unsplash

Deal with relative path is not a complex thing, but when we are creating an application using create-react-app sometimes it could be a tough work. To configure paths and other configurations we usually use Babel, but Babel is not available to edit when we create an app using create-react-app, unless you eject.

In this post I will show you how to change path configuration using Babel without eject your application. Let’s create an app using create-react-app called react-relative-path:

$ create-react-app react-relative-path

Now, I will create some folders, add some components and add references to each other.

First create a folder called Api and add a Item.js file.

And a folder called Components with subfolders ListItems and Item as we can see below:

On App.js we just import and use the component Item:

The result should be like this:

Alright, everything is working well, but if you decide to change the folder structure? Remember the path inside Item component:

import item from '../../../Api/Item';

If you decide to remove the folder ListItems and let only the folder Item:

Now we have an error:

We have to change all paths inside all components inside Item folder, of course in this case is easy, but imagine you have many components, I could be hard to maintain.

In order to deal with this situation, we can use some third-part components. This first we need to install is the react-app-rewired. This component allow us to change webpack configuration without using ‘eject’ and without creating a fork of the react-scripts:

npm i --dev react-app-rewired

The second component the babel-plugin-root-import, that allow us to import components using root based paths.

npm i --dev babel-plugin-root-import

Alright, now we need create a file on root folder called config-overrides.js:

In this file we are going to configure basically two things: the root prefix and root sufix. The rootPathPrefix is the character we would like to use to refer the root folder and the rootPathSuffix is the name of the root folder.

Next step is change the package.json file to use the react-app-rewired (except the eject script):

Finally let’s change the Item component to use the new prefix “~”:

And now it’s working again:

If you are using VSCode, I have one more tip. After these changes we’ve made, you can see we lost the intellisense for paths. So, after you type ~/… the VSCode will not complete or suggest the available path. To fix this, we need to add a file called jsconfig.json and add some configs:

The most important part is the “paths” section. In this section we instruct the VSCode to map the path “~/” to “./src” and after that the intellisense will work again:

You can clone this project here: https://github.com/lblima/react-relative-path

That’s all folks,

Thanks for reading!

--

--