3

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 2

6

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: on github and on the npm js blog.

Sign up to request clarification or add additional context in comments.

Comments

1

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'],
}

3 Comments

Do you mean, transpiling an bundling phases actually do not care if a dependency is peer, dev or normal?
@helt they do care. If it's a peer dependency it's not included in the bundle but as you have in the question you'll also have to include them in the dev dependencies. This opens up the chance for version mismatches as packages get updated in one place but not the other. Using externals is safer.
I see. with externals, I would at least save duplicate version definitions, which is dryer than before :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.