'how to use absolute paths instead of relative paths in React or Next.js?

I'm using React and I have multiple components that I use in multiple higher-order components, my imports sometimes will be like this import MyComponent from '../../../../components/MyComponent' I know there is a more efficient way to import this by changing something inside the package.json file and then import it somewhat like this import MyComponent from '@components/myComponent' but I don't remember how can I do this, how can I do this?



Solution 1:[1]

Create a jsconfig.json in the root directory and copy the below code. Restart VSCode for the changes to apply -

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@components/*": ["src/components/*"],
        }
    }
}

Solution 2:[2]

in next.js, this works for me=>

In root folder, create jsconfig.json( tsconfig.json if using typescript) file. Then add this

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

create a "components" folder in root file, then it will be like this :

// components/button.js

export default function Button() {
  return <button>Click me</button>
}


// App.js

import Button from 'components/button'

 export default function HomePage() {
    return (
     <>
      <h1>Hello World</h1>
      <Button />
     </>
   )
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dhilip H
Solution 2