Advertisement
MaikoTan

Yarn PnP API Usage

May 26th, 2024 (edited)
630
-1
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 2.02 KB | Software | 0 1
  1. import { readFileSync } from 'node:fs'
  2. import { createRequire } from 'node:module'
  3. import { dirname, join } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5.  
  6. let pnp: typeof import('pnpapi') | undefined = undefined
  7.  
  8. if (process.versions.pnp) {
  9.   try {
  10.     pnp = createRequire(import.meta.url)(`pnpapi`)
  11.   } catch {}
  12. }
  13.  
  14. function test() {
  15.   if (!pnp) {
  16.     console.log(`Running in Node.js environment`)
  17.     return
  18.   }
  19.  
  20.   console.log(`Running in PnP environment`)
  21.  
  22.   if (typeof pnp.VERSIONS['getAllLocators'] !== `number`) {
  23.     console.error(`The version of the PnP API is too old`)
  24.     process.exit(1)
  25.   }
  26.  
  27.   pnp.getDependencyTreeRoots().forEach(locator => {
  28.     const info = pnp.getPackageInformation(locator)
  29.     console.log(`- ${locator.name}: (${info.packageLocation})`)
  30.   })
  31.  
  32.   // Get all the packages in current workspace
  33.   pnp.getAllLocators().forEach(locator => {
  34.     const info = pnp.getPackageInformation(locator)
  35.     console.log(`  - ${locator.name}: (${info.packageLocation})`)
  36.   })
  37.  
  38.   const baseDir = dirname(fileURLToPath(import.meta.url))
  39.  
  40.   // Get one package information by name
  41.   const normalised = pnp.resolveToUnqualified(`esbuild`, baseDir, { considerBuiltins: false })
  42.   if (!normalised) {
  43.     console.error(`Package not found`)
  44.     process.exit(1)
  45.   }
  46.  
  47.   const locator = pnp.findPackageLocator(normalised)
  48.   console.log(JSON.stringify(locator, null, 2))
  49.   const info = pnp.getPackageInformation(locator)
  50.   console.log(JSON.stringify(info, null, 2))
  51.   // -->
  52.   // {
  53.   //   "packageDependencies": {},
  54.   //   "packagePeers": {},
  55.   //   "linkType": "HARD",
  56.   //   "discardFromLookup": false,
  57.   //   "packageLocation": "E:\\repo\\koishi\\cordis-test\\.yarn\\cache\\koishi-npm-4.17.7-43020a5508-08ffffd724.zip\\node_modules\\koishi\\"
  58.   // }
  59.  
  60.   const pkgData = join(normalised, `package.json`)
  61.   const pkg = readFileSync(pkgData, `utf8`)
  62.   {
  63.     const { name, version } = JSON.parse(pkg)
  64.     console.log(`Package: ${name}@${version}`) // --> Package: koishi@4.17.7
  65.   }
  66. }
  67.  
  68. test()
  69.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement