Making a dependency's dependencies available with Yarn 2
Asked Answered
P

1

7

I'm working on a framework where I want the dependencies of the framework package to be available to the application which consumes it. The dependencies are not directly used by the consumer, but by the files provided by the framework.

With npm, it works, but with Yarn 2 I get errors like this

Error: Your application tried to access @snowpack/plugin-dotenv, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

Obviously I can just add the dependencies to the package.json of the consuming app, but that requires manual editing of package.json whenever dependencies change. This goes against the idea of a framework with a no-fuzz upgrade path. Additionally, the dependencies are for files supplied by the framework. They shouldn't be interfered with by downstream code.

Is it possible to share dependencies downstream?

Note: I'm using workspaces. I don't know if that's relevant to the question.

Porcupine answered 10/6, 2020 at 7:51 Comment(1)
Switched to pnpm and its "--shamefully-hoist" option.Porcupine
S
3

You can use createRequire to achieve that.

For example if your application has a dependency on [email protected] and you want in the application code to require its sub-dependency picomatch without declaring it, you can do it on behalf of micromatch via the code below:

const {createRequire} = require(`module`);
const requireDependency = createRequire(require.resolve(`micromatch`));
requireDependency(`picomatch`);

This approach will work with all package managers and install strategies, including Yarn v2 pnp and pnpm and npm too.

Serigraph answered 7/10, 2020 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.