Created
May 16, 2023 20:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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