Search code examples
javascriptreactjsreact-boilerplate

How to refer components without typing the complete relative path?


src
    components
        HomePage
            Calendar.js
    containers
        HomePage
            index.js

I'm just using the recommended folder structure in React(Presentation + Container). While I was working on react-boilerplate folder structure, I can refer Components inside components folder with out listing the relative path, import Calendar from 'components/HomePage/Calendar';. How to do that in my project, without typing the full relative path, import Calendar from '../../components/HomePage/Calendar'; ?


Solution

  • Create jsconfig.json or tsconfig.json depending on your project, javascript or typescript respectively.

    Inside the json file.

    1. baseUrl is the folder of all your folders like component, container and contexts located.
    2. inside paths json the keys are the folders inside the baseUrl folder, but you can't specify each folders inside the parent folder.

    My project snippet.

    {
      "compilerOptions": {
        "baseUrl": "src",
        "paths": {
          "screens/*": ["src/screens/*"],
          "components/*": ["src/components/*"],
          "utils/*": ["src/utils/*"]
        }
      }
    }
    

    Like this way.

    {
      "compilerOptions": {
        "baseUrl": "your top most parent folder",
      }
    }