loading...

Absolute imports with create-react-app and VSCode

oliverandrich profile image Oliver Andrich ・1 min read

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.

Posted on by:

oliverandrich profile

Oliver Andrich

@oliverandrich

Loves coffee, code and a good conversation.

Discussion

pic
Editor guide