Search code examples
node.jsreactjsnpmdependenciespackage.json

What is the correct way of adding `react` as a dependency in the `package.json` of a reusable components library?


I built a few reusable React components, and I want to know the correct way to add react as a dependency in my package.json for the purpose of publishing to the npm registry.

I am currently doing this:

I assume that my component will use the most recent version of React, and I test that it works with the said version, e.g. 0.13.3:

"peerDependencies": { 
    "react": "^0.13.3"
},

Solution

  • For reusable components:

    1. Put a react dependency in both peerDependencies and devDependencies.
    2. Never put a react dependency in dependencies.

    peerDependencies specifies which version(s) of React your reusable component supports/requires. When using npm 2 this also adds React to the list of modules to be installed, but this is no longer the case with npm 3.

    devDependencies ensures React will be installed when you run npm install while developing your component, or when running tests on Travis or similar.

    Putting react in dependencies will cause multiple versions of React to be installed if somebody uses your component but has a different version of React in their own package.json - having multiple versions of React not only bloats the build, but also causes errors when different versions try to interact.