DEV Community

Cover image for How Pros Get Rid of Relative Imports

How Pros Get Rid of Relative Imports

Tapajyoti Bose on September 12, 2021

If you have worked on a decently sized Node.js application regardless of whether its JavaScript or TypeScript, you will have come across long impor...
Collapse
 
richardeschloss profile image
Richard Schloss • Edited

subpath patterns can also be used in package.json. I like to think of it as a cool free feature baked right in to nodejs.

For example:

{
  "exports": {
    "./features/*": "./src/features/*.js"
  },
  "imports": {
    "#internal/*": "./src/internal/*.js",
    "#root/*": "./"
  }
}
Enter fullscreen mode Exit fullscreen mode

This way, it's tied to the node project, which will work no matter what the IDE is.

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Thanks a lot for sharing! I wasn't aware of this feature

Collapse
 
talorlanczyk profile image
TalOrlanczyk • Edited

Its great but unfortunately react by itse will ignore paths

Collapse
 
damiisdandy profile image
damilola jerugba

I read somewhere it only doesn’t work for create-react-app, did you test it on CRA?

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Since this is quite a useful trick, even though it doesn't work directly, there is a work around for it

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

I think it works with React as well. Tried it in a Next.js project though

Collapse
 
talorlanczyk profile image
TalOrlanczyk

For react you need third party library

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose

I tested it right now, it's working with plain old react

Collapse
 
urafiz profile image
UraFIZ

You are 😎

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

😅

Collapse
 
pinich profile image
Pini Cheyni

I was using it in angular/nestJS project for a while. I had no idea it was such a big deal.
This works very well for shared libraries in a monorepos.

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Yeah, it helps a lot to ease repeatative directory traversal

Collapse
 
alfianandinugraha profile image
alfianandinugraha

Absolute path really help me when use typescript. I also make boilerplate for reactjs and typescript with absolute path create-react-typescript-app.vercel...