Skip to content

Instantly share code, notes, and snippets.

@albertms10
Last active October 24, 2023 21:45
Show Gist options
  • Save albertms10/808330d52f3b9f742d34fc21f601891e to your computer and use it in GitHub Desktop.
Save albertms10/808330d52f3b9f742d34fc21f601891e to your computer and use it in GitHub Desktop.
Yarn workspaces dependencies
import { execSync } from 'child_process';
import { parseArgs } from 'node:util';
export const { values: args } = parseArgs({
options: {
workspace: { type: 'string', short: 'w' },
},
});
const foundDependencies = new Set();
const targetApplication = args['workspace'];
const targetWorkspace = findWorkspace(targetApplication);
if (!targetWorkspace) {
console.error(`Unable to find workspace for ${targetApplication}`);
process.exit(1);
}
console.info(`Dependencies for ${targetApplication}:`);
buildDependencyList(targetWorkspace.name);
console.log(foundDependencies);
function findWorkspace(targetApplication) {
// Get monorepo workspace information
const listOutput = execSync('yarn workspaces list --json', {
encoding: 'utf-8',
});
// Parse the output to extract workspace information
const workspaces = listOutput
.split('\n')
.filter(Boolean)
.map((workspace) => JSON.parse(workspace));
// Find the workspace path for the target application
return workspaces.find((workspace) => workspace.name === targetApplication);
}
// Recursively build the dependency list
function buildDependencyList(workspaceName) {
const output = execSync(`yarn why --json ${workspaceName}`, {
encoding: 'utf-8',
});
const dependencies = output
.split('\n')
.filter(Boolean)
.map((dependencies) => JSON.parse(dependencies));
dependencies.forEach(({ value }) => {
const [, rawName] = value.split('@');
const name = `@${rawName}`;
foundDependencies.add(name);
buildDependencyList(name);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment