React import root path helper

Viewed 30701

In react because I have to import varies helper or component I have this problem

import approxPerDay from '../../../utils/approxPerDay.js'
import otherstuff from '../components/otherstuff'

and in another file it might be import approxPerDay from '../utils/approxPerDay.js'

It's really hard and time consuming to find is the relative path is. Is there any npm or helper can solve this issue?

4 Answers

The thing you are asking is called "absolute import". "create react app" already provides a standard solution and recommends creating a jsconfig.json file in your root directory of react project.

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

Later you can import components as such:

import Button from 'components/Button';

Go to this link of official docs related to importing component and there u will find absolute import section:

https://create-react-app.dev/docs/importing-a-component/

And Yes don't forget to restart your react server after doing the changes : )

If you need to specify the .env file and relative path, the IDE needs to know about it. For this, the following lines worked for on my IDE.

File jsconfig.json

{
    "compilerOptions": {
        "baseUrl": "src"
    },
    "include": [
        "src"
    ]
}

enter image description here

Related