172 words
1 minute
Absolute Component Imports

Absolute imports in React allow you to import components with ease without worrying about where the directory of the component is relative to the one you’re importing to. Say we have componentA located in src/components/navbar/componentA.js/ and componentB in src/componentB.js. In code that looks like this:

To import our componentB into componentA it would look like this with an absolute import

import "componentB" from "src/componentB"

With a relative import it looks like this

import "componentB" from "../../componentB"

That can get real annoying real fast.

To set this up you can do it with one of two ways. If you’re using Create React App 3.0 or higher, use this way:

create a new file in the same directory as your package.json called jsconfig.json. Inside the following code in the file

{
  "compilerOptions": {
    "baseUrl": "src"
  }
}

If you aren’t using Create React App 3.0 do it this way:

create a file in the same directory as your package.json and name it .env. Inside of the file put the following code

NODE_PATH=/src

Once you restart your app you should be able to start using absolute imports!!

Absolute Component Imports
https://edwardbeazer.com/posts/absolute-component-imports/
Author
Edward Beazer
Published at
2019-05-24