Warm tip: This article is reproduced from stackoverflow.com, please click
phpstorm react-router-dom webstorm node-modules jetbrains-ide

PhpStorm can't resolve package import even though it exists (react-router-dom)

发布于 2020-04-09 22:55:45

I am using React (16.12.0) with PhpStorm (2019.3.1).

The package I am importing is react-router-dom (5.1.2)

I will write the following import:

import { NavLink, Switch } from "react-router-dom";

Both packages are imported properly by webpack/babel and the page renders properly when I use both Switch and NavLink.

However purely from the IDE-perspective, I get a warning about Switch: Cannot resolve symbol 'Switch'

It is weird because it is obviously there, and I checked in /node_modules/react-router-dom and Switch.js is there.

Strangely on previous versions of PhpStorm (before several updates and plugin imports and other changes), the Switch import was accurately found by PhpStorm.

I have not updated react-router-dom recently and am using its latest stable build.

Any ideas as to why it might be missing Switch?

EDIT: I have realized it may be because PhpStorm is having difficulty importing a commonJS module.

I tried changing the Javascript compilation method from React JSX to ECMA 6. That didn't work.

I also tried importing some build libraries for react-router-dom, and that worked for recognizing the Route import strangely but not Switch.

I also tried invalidating the PhpStorm cache and restarting the app, but that didn't work either.

EDIT 2: Per an answer, I have tried to use option+enter (alt+enter on windows) while my cursor is within react-router-dom to try to install a typescript package, but I don't get the same suggested action as shown on the JetBrains website: https://www.jetbrains.com/help/webstorm/configuring-javascript-libraries.html

All it suggests is switching single quotes to double quotes.

enter image description here

Also I have already installed @types/react-router-dom. Perhaps there is another one that I am missing?

enter image description here

EDIT 3: The correct answer was to install @types/react-router. For some reason @types/react-router-dom is deceivingly NOT what solves this.

Questioner
willsmanley
Viewed
250
lena 2020-02-02 05:09

node_modules/react-router-dom/esm/react-router-dom.js exports BrowserRouter, HashRouter, Link and NavLink, but doesn't export Switch, it's not explicitly defined there. For better completion/type hinting, you can install Typescript stubs for the package: put cursor on "react-router-dom" in import statement, hit Alt+Enter, choose Install TypeScript definitions for better type information::

enter image description here

See https://www.jetbrains.com/help/webstorm/2019.3/configuring-javascript-libraries.html#ws_jsconfigure_libraries_ts_definition_files