Search code examples
dependenciesyarnpkgyarnpkg-v2

Making a dependency's dependencies available with Yarn 2


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.


Solution

  • You can use createRequire to achieve that.

    For example if your application has a dependency on micromatch@4.0.2 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.