DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Oliver Andrich
Oliver Andrich

Posted on

Absolute imports with create-react-app and VSCode

In my projects, I never thought about switching to importing modules using absolute paths. But recently a colleague new to React asked if it is possible in his project. He got a bit annoyed by all these dots and slashes.

import LoginButton from "../../components/LoginButton".

Being able to use absolute paths in every place looks more beautiful and makes refactoring of code also a bit easier.

import LoginButton from "components/LoginButton".

We are using create-react-app to start all our projects. So, adding it to the project was easy. We just had to follow the steps from this guide and create a file named jsconfig.json in the root of your project with the following content.

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

A little extra effort was necessary to configure VSCode and ESLint to support it. We usually use the standard rules from eslint-plugin-import to add some additional error checking while editing our code.

{
  "extends": ["react-app", "plugin:import/errors", "plugin:import/warnings"],
}

To support absolute paths in VSCode, we had to extend this configuration like that.

{
  "extends": ["react-app", "plugin:import/errors", "plugin:import/warnings"],
  "settings": {
    "import/resolver": {
      "node": {
        "moduleDirectory": ["node_modules", "src/"]
      }
    }
  }
}

Cheers! And bye, bye to all these pleonastic dots and slashes.

Top comments (1)

Collapse
 
ahmedadelbayoumi profile image
Ahmed Adel

Thank you so much for the "moduleDirectory" configuration.

Now it's your turn.

Β 
πŸ—’ Share a tutorial
πŸ€” Reflect on your coding journey
❓ Ask a question
Β 
Create an account to join hundreds of thousands of DEV members on their journey.