'How to enable VS code intellisense for absolute path imports in a React app?

So, i recently created a React app and added the absolute imports by updating the jsconfig.json for my project as per the documentation (https://create-react-app.dev/docs/importing-a-component/#absolute-imports). Now I am able to use absolute imports inside my project, but now VS code intellisense seems to be broken, as I don't get autosuggestions for absolute paths. Can anybody point what the reason may be ?



Solution 1:[1]

I follow the cra docs and suffer from the same issue, I found the solution which modifies baseUrl from src to ./src , hope this can help you!

// jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src"
  },
  "include": ["src"]
}

// .eslintrc
{
  "settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      }
    }
  }
}

Solution 2:[2]

Perhaps somebody will find it useful - here is how to handle path aliases:

  • jsconfig.json (the only file we need to add / modify for Vscode to recognize imports):
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "@c/*": ["./src/components/*"],
      "@h/*": ["./src/helpers/*"],
      "~/*": ["./node_modules/*"]
    }
  }
}
  • path aliases resolved in webpack.config.js:
resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src/'),
    '@c': path.resolve(__dirname, 'src/components/'),
    '@h': path.resolve(__dirname, 'src/helpers/'),
    '~': path.resolve(__dirname, 'node_modules/')
  }
},

Now, when I type, for exaple, @c/, Vscode provides autocomplete hints correctly, showing the content of src/components folder, or when I "ctrl-click" on the import @c/Navbar, the file src/components/Navbar.js gets opened, everything works as expected.

And thanks to the author of the previous reply for the hint about jsconfig.json.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay Pan
Solution 2