Absolute Component Imports

Import components with absolute imports instead of doing relative(../../componentName)

Fri, 24 May 2019

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!!

Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.