Search code examples
yarnpkgyarn-workspacesyarnpkg-v2yarn-v2

Can the Yarn 2 Constraints feature block the installation of a package?


I have a deep dependency tree. Some of the packages depend on nodejs packages that I don't need. Is it possible for Yarn 2 (berry) to skip those packages, i.e. not install them?

Yarn has a Constraints feature, but I don't know what's possible with it. There are examples, but not for ignoring a package completely.

Is this possible? Thanks


Solution

  • Constraints allow you to enforce rules on the dependency your project (and workspaces) have. It's a tool for writing rules that are applied to what goes in your various package.json files, like "every workspace must have the same version of react" or "no workspace may depend on package X".

    If you have a dependency that is depending on something that you believe is really an optional dependency, you can use .yarnrc to change that dependency into an optional one. Use yarn why <foo> find the package that is causing the unwanted deep dependency, and then add something like this to .yarnrc (specific example yoinked from here):

    # Make `eslint-plugin-flowtype`'s peerDependency on `@babel/plugin-syntax-flow` optional.
    # Use `dependenciesMeta` for non-peer deps, of course ;).
    packageExtensions:
      'eslint-plugin-flowtype@*':
        peerDependenciesMeta:
          '@babel/plugin-syntax-flow':
            optional: true
    

    Note that doing this is in general quite risky: you should probably be filing a bug upstream if you think a package is depending on something that should really be an optional dependency.

    Lastly, note that it's very possible this whole thing is a non-problem: webpack (or whatever bundler is in fashion a week after I write this) is probably deleting the unwanted files at compile-time anyway? If you find the mere presence of the node packages you don't like is causing issues (eg. via typescript typings?) then that's a different problem that should be solved differently.