Search code examples
reactjstypescriptreact-routeryarnpkg

What's the difference between `yarn add react-router-dom` and `yarn add @types/react-router-dom`?


Doing

yarn add react-router-dom

fails. The app throws an error on startup and Intellij flags the import from react-router-dom it as an error. But doing

yarn add @types/react-router-dom

works.

All the examples I've found except for one show the first yarn add... command, though. Is this something new with react-router-dom?

I'm using typescript if that makes any difference.

===Edit===

Here is the error message. This is where I found the solution.

/home/dean/src/react/projects/room-reservations-ui_/src/App.tsx
TypeScript error in /home/dean/src/react/projects/room-reservations-ui_/src/App.tsx(5,29):
Could not find a declaration file for module 'react-router-dom'. '/home/dean/src/react/projects/room-reservations-ui_/node_modules/react-router-dom/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/react-router-dom` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-router-dom';`  TS7016

    3 | import './App.css';
    4 | import Navbar from "./components/Navbar";
  > 5 | import {BrowserRouter} from "react-router-dom";
      |                             ^
    6 | 
    7 | function App() {
    8 |   return (

Solution

  • yarn add react-router-dom
    

    This is installing react-router-dom, without any types, if you try to start your app just with this package, you will see the message you got

    Could not find a declaration file for module 'react-router-dom'.
    

    This doesn't mean that there is an error with the react-router-dom, but Typescript don't have the types declared for it, the project could have been made with Javascript, or the type declarations are somewhere else.

    yarn add @types/react-router-dom
    

    This will install the types for react-router-dom from DefinitelyTyped(https://github.com/DefinitelyTyped/DefinitelyTyped), this is a repository where declarations are made so we can install types for libraries that were made just for Javascript, but someone else "typed" it for us.

    @types/
    

    This prefix is an organization, which will refer to the react-router-dom package inside the DefinitelyTyped repository, it doesn`t contain react-router-dom code, only the type definitions, which you can see here https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-router-dom

    It contains only the declaration, when Typescript can't find declarations for a module you are using, it won't be able to correctly show you the types, so it gives the warning