Skip to content

Instantly share code, notes, and snippets.

@jcreamer898
Created May 16, 2023 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcreamer898/682f04cfc5bfe3b751e05555011259ae to your computer and use it in GitHub Desktop.
Save jcreamer898/682f04cfc5bfe3b751e05555011259ae to your computer and use it in GitHub Desktop.
A simple way to get the path to the root package.json in a monorepo.
const getRootPackageJsonRecursively = async () => {
let currentDir = __dirname;
let packageJson;
let nextDir = "";
while (currentDir) {
try {
packageJson = await fs.readFile(
path.join(currentDir, "package.json"),
"utf8"
);
const pkg = JSON.parse(packageJson);
if ("workspaces" in pkg) {
break;
} else {
throw new Error("No workspaces");
}
} catch (/** @type {any} */ e) {
nextDir = path.dirname(currentDir);
if (nextDir === currentDir) {
currentDir = "";
} else {
currentDir = nextDir;
}
}
}
return path.join(currentDir, "package.json");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment