Skip to content

Instantly share code, notes, and snippets.

@waynebloss
Last active February 3, 2022 15:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waynebloss/096168e42dbdb04b26b71c9058e25fda to your computer and use it in GitHub Desktop.
Save waynebloss/096168e42dbdb04b26b71c9058e25fda to your computer and use it in GitHub Desktop.
Testing yarn alias with Deep Dependencies

Testing yarn alias with Deep Dependencies

Yarn tip: You can alias a package by using yarn add fake-name@npm:left-pad. Now you can use require("fake-name") to require left-pad.

This could be useful for module level dependency injection or inversion of control...

TLDR; This works for peerDependencies of your dependencies,

but not for dependencies of your dependencies. See test 3.

The Idea

So we'll try it with get-query-param which depends on query-string v5.0.0 which we will replace with qs.

The Setup

Create a new project with yarn init.

Test 1

  1. yarn add query-string@npm:qs
  2. yarn add get-query-param

Result: Failure

get-query-param got its own copy of query-string in node_modules/get-query-param/node_modules/query-string.

Test 2

  1. yarn add query-string@npm:qs get-query-param

Result: Failure

get-query-param got its own copy of query-string in node_modules/get-query-param/node_modules/query-string.

Test 3 (with peerDependencies)

  1. Clone get-query-param to ../get-query-param2, change the package name and move query-string from dependencies to peerDependencies in its package.json.
  2. yarn add query-string@npm:qs
  3. yarn add file:./../get-query-param2
  4. copy test.js from node_modules/get-query-param2 to project root and modify its import, then run yarn add ava, add scripts: { test: 'ava -v'} to your own package.json and then run yarn test.

Result: Success!

get-query-param2 uses qs as its query-serializer and all tests pass.

@joshuapinter
Copy link

Interesting. So the only way to fix this is by forking the packages that list the package you're trying to alias and moving it to peerDependencies?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment