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

橙三吉。 提交于 2021-01-27 16:02:23

问题


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.

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

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


回答1:


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::

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



来源:https://stackoverflow.com/questions/60015377/phpstorm-cant-resolve-package-import-even-though-it-exists-react-router-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!