Best practices for using `peerDependency`and `devDependency`

Viewed 2575

I am writing a react component library, and dont want to bundle react, so I added the libs to peerDependencies rather than dependencies.

Also, to prevent those stupid warnings about missing peerDependencies, I add the same libs to the devDependencies section.

Thats not DRY, but a fixed warning is more important to me than a DRY package.json.

So the question is: Is there a DRYer method to achieve this, or do I actually follow the May 2020 best practice?

{
    "peerDependencies": {
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "tslib": "^1.11.0",
    },
    "devDependencies": {
        "@types/react": "^16.9.0",
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "typescript": "^3.8.0"
    },
    "dependencies": {
        // nothing here
    }
}

2 Answers

For npm >= v7, npm announced to autoinstall peerDependency packages.

So, just remove the deps from devDependencies, if they are already listed in the peerDependencies section like this:

{
    "peerDependencies": {
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "tslib": "^1.11.0",
    },
    "devDependencies": {
        "@types/react": "^16.9.0",
        "typescript": "^3.8.0"
    },
    "dependencies": {
        // nothing here
    }
}

For npm < 7, follow @gcastros answer.

--

See also: https://github.com/npm/rfcs/blob/latest/accepted/0025-install-peer-deps.md https://blog.npmjs.org/post/617484925547986944/npm-v7-series-introduction

I'm not sure what you're using to create your bundle but if you're using Webpack or Rollup you can define externals not to be included in the bundle.

In your care everything you have in peerDependencies would go into dependencies and in the config for webpack or rollup you'd define the externals as follows:

{
  ...
  externals: ['react', 'react-doe', 'tslib'],
}
Related