[ Home ] [ About ][ Posts ][ Git ][ Contact ][ Links ][ Bookmarks ]

How to setup absolute import in react

Estimated reading time: 1 minutes

React components imports can have a very very long relative file path if you are in a big project, here is how to solve the issue instead of writing a lot of .. .. .. and .. Credits to Eric Murphy

For example you have

import React from "react";
import Button from "../../../components/Button";
import logo from "../../../../logo.svg";

const NestedComponent = () => {
    return (
            <img src={logo} alt="logo" />
            <Button />

export default NestedComponent;

Assuming your components folder and logo.svg is in src folder

|— logo.svg
|— components
|— Button.js

You can change your import to

import Button from "components/Button";
import logo from "logo.svg";

But this ain’t gonna work, so we need to create jsconfig.json in root directory

// jsconfig.json

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

If you are using Typescript, compilerOptions object will already be in tsconfig.json. Then just add "baseUrl": "src" to the object