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

Time:10-07

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

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!

CodePudding user response:

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.

CodePudding user response:

Alternatively, you can let your IDE do the work for you (importing and moving files around). The gif below is WebStorm, I believe MS Code does it too.

enter image description here

CodePudding user response:

You can use babel-plugin-module-resolver.

This plugin can simplify the require/import paths in your project. For example, instead of using complex relative paths like import dataJSON from "../../data/data.json";, you can write import dataJSON from "data/data.json";. It will allow you to work faster since you won't need to calculate how many levels of the directory you have to go up before accessing the file.

Install the plugin

npm install --save-dev babel-plugin-module-resolver

or

yarn add --dev babel-plugin-module-resolver

Create a jsconfig.json file and use the code.

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

That's it.

  • Related