Skip to content
Advertisement

How to get Visual Studio Code to navigate to a React component’s source file?

Consider a typical ReactJS file, like:

import Popup from 'components/Popup/Popup';

// ...

<Popup
  trigger={
    <SVG src={pinIcon} className={pinClassName} />
  }
  content={pinTooltipText}
  position="bottom center"
  hideOnScroll
  className="popup-xl--hide"
/>

In VS Code, I want to go to the file that is my component, so jump to components/Popup/Popup. Using Go To Definition:

Go To Definition in VS Code

It sends me up to the import declaration. I can’t jump to that file. This is a pain to manage as we have dozens of components and properties moving through them all. Being able to quickly navigate “down” the component stack by going to each definition would be mind-numbingly awesome.

Advertisement

Answer

If you have import aliases, through webpack or babel, you can create a jsconfig.json file with the paths property in the compilerOptions.

Here’s a Next project’s jsconfig.json configured for @/ aliases to the src/ directory.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2017",
    "jsx": "react",
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
    }
  },
  "exclude": [
    "node_modules",
    "dist",
    ".next",
    ".cache",
    "bundles",
    "out"
  ],
  "include": [
    "pages/**/*",
    "src/**/*",
  ]
}

It may be needed to restart VS Code, then you should be able to CTRL+click any <Component> or import paths to navigate to it.

VS Code component navigation

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement