Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to customize the initial path to the route of the folder in react?

When I am doing import of different files I have to be very careful on the folder nesting where do I call the imports.

I know that it is possible to set a generic variable path to import files directly pointing at the route of my SRC folder, but I never done it and I am just unable to find the information on the web about it on how to configure it (every search come around react-router which is not what I need). Could someone explain me how to make it happen:

import dataJSON from "../../data/data.json";
import IconPath from "../../assets/svg/icons.svg";

become something approximate like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import dataJSON from "{myRoute}/data/data.json";
import IconPath from "{myRoute}/assets/svg/icons.svg";

so that I don’t have to worry all the time to think about nest depth when I code and organise my components in folders.

Thank you!

>Solution :

For Javascript :

Create a jsconfig.json file in the root of your project with the following content:

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

For Typescript:

You already have tsconfig.json file in the root of project. Just need to add baseurl setting in compile options key.

{
...//other ts config
"compilerOptions": {
    ..., // other complie options
    "baseUrl": "src"
  },
...//other ts config
}

Here baseUrl is what we’re adding into compileoptions.

after adding this file and configuration you can import files as following.

Before:

import Component1 from '../../../../Components/Component1'

After:

import Component1 from 'Components/Component1'

Anything you import will be absolute imports from src folder.

Hope this is what you’re looking for.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading