{"id":12773,"library":"pkg-types","title":"Package and TypeScript Configuration Utilities","description":"pkg-types is a utility library providing Node.js functions and comprehensive TypeScript definitions for common project configuration files, including `package.json`, `tsconfig.json`, and various lock files (e.g., `yarn.lock`, `pnpm-lock.yaml`, `bun.lockb`, `deno.lock`). The current stable version is 2.3.0. The package has an active development cycle, with frequent releases bringing enhancements and bug fixes. A key differentiator is its automatic format detection for `package.json` (supporting `.json`, `.json5`, `.yaml`) and robust utilities for finding and reading workspace configurations across different package managers and monorepo tools like Lerna, Turborepo, and Rush. It streamlines the process of programmatically interacting with project metadata, making it ideal for tooling development.","status":"active","version":"2.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/unjs/pkg-types","tags":["javascript","typescript"],"install":[{"cmd":"npm install pkg-types","lang":"bash","label":"npm"},{"cmd":"yarn add pkg-types","lang":"bash","label":"yarn"},{"cmd":"pnpm add pkg-types","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary utility for reading `package.json`, `package.json5`, or `package.yaml` files with automatic format detection. The package became ESM-only in v2.0.0.","wrong":"const readPackage = require('pkg-types')","symbol":"readPackage","correct":"import { readPackage } from 'pkg-types'"},{"note":"Import `PackageJson` as a type for robust type-checking of `package.json` structures. It should be imported with `type` for tree-shaking and avoiding runtime overhead.","wrong":"import { PackageJson } from 'pkg-types'","symbol":"PackageJson","correct":"import type { PackageJson } from 'pkg-types'"},{"note":"Utility for reading `tsconfig.json` files. This is a named export, not a default export.","wrong":"import readTSConfig from 'pkg-types'","symbol":"readTSConfig","correct":"import { readTSConfig } from 'pkg-types'"},{"note":"Locates the root directory of a workspace, supporting various monorepo configurations and lock files. Requires a named import.","symbol":"findWorkspaceDir","correct":"import { findWorkspaceDir } from 'pkg-types'"}],"quickstart":{"code":"import { readPackage, findPackage, readTSConfig, findWorkspaceDir } from 'pkg-types';\nimport path from 'node:path';\n\nasync function getProjectConfig() {\n  try {\n    // Find the nearest package.json, package.json5, or package.yaml\n    const packageFile = await findPackage(process.cwd());\n    if (packageFile) {\n      console.log(`Found package file: ${packageFile}`);\n\n      // Read the package configuration, automatically detecting format\n      const pkg = await readPackage(path.dirname(packageFile));\n      console.log('Project Name:', pkg.name);\n      console.log('Project Version:', pkg.version);\n    } else {\n      console.log('No package file found in current directory or ancestors.');\n    }\n\n    // Read the nearest tsconfig.json\n    const tsconfigPath = await findPackage(process.cwd(), { filenames: ['tsconfig.json'] });\n    if (tsconfigPath) {\n      const tsconfig = await readTSConfig(path.dirname(tsconfigPath));\n      console.log('TSConfig Compiler Options:', tsconfig?.compilerOptions);\n    } else {\n      console.log('No tsconfig.json found.');\n    }\n\n    // Find the workspace root directory\n    const workspaceRoot = await findWorkspaceDir(process.cwd());\n    if (workspaceRoot) {\n      console.log('Detected workspace root:', workspaceRoot);\n    } else {\n      console.log('No workspace root detected.');\n    }\n\n  } catch (error) {\n    console.error('Failed to read project configuration:', (error as Error).message);\n  }\n}\n\ngetProjectConfig();","lang":"typescript","description":"Demonstrates how to find and read project `package.json` and `tsconfig.json` files, and detect the workspace root directory using various utilities from `pkg-types`."},"warnings":[{"fix":"Migrate your project to use ES module `import` syntax. Ensure your `package.json` has `\"type\": \"module\"` or use `.mjs` file extensions for files importing `pkg-types`.","message":"Starting with v2.0.0, `pkg-types` is an ESM-only distribution. CommonJS `require()` statements will no longer work and will result in runtime errors.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Update parsing logic to account for both `string[]` and `object` types for the `workspaces` field when reading `PackageJson` data.","message":"The `workspaces` field in `package.json` now supports an object format in addition to arrays since v2.3.0. If your tooling expects only array formats, ensure it can gracefully handle the new object structure.","severity":"gotcha","affected_versions":">=2.3.0"},{"fix":"When explicit behavior is needed, specify the full file path to functions like `readPackage` instead of relying solely on directory-based discovery. Alternatively, manage your project's configuration files to avoid ambiguity.","message":"`readPackage` and `findPackage` support multiple file formats (`package.json`, `package.json5`, `package.yaml`) and will automatically detect them. If you expect a specific format, ensure your directory doesn't contain conflicting files that might lead to unexpected reads.","severity":"gotcha","affected_versions":">=2.3.0"},{"fix":"Familiarize yourself with the `findWorkspaceDir` detection order documented in the README. If the default strategy is not suitable, consider using more specific file resolution functions like `findPackage` with custom `filenames` options.","message":"`findWorkspaceDir` employs a specific detection strategy (workspace config files, `.git/config`, lockfiles, then `package.json`). In complex monorepo setups, understanding this order is crucial for predictable results.","severity":"gotcha","affected_versions":">=2.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Replace `const { ... } = require('pkg-types')` with `import { ... } from 'pkg-types'`. Ensure your Node.js environment or build setup correctly handles ES modules.","cause":"Attempting to use `require()` to import `pkg-types` in an environment where it's treated as an ES module.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Verify that a valid package configuration file exists in the target directory or any parent directories. Ensure the provided path is correct and accessible. Handle the potential error in your application logic.","cause":"The `findPackage` or `readPackage` utility could not locate any `package.json`, `package.json5`, or `package.yaml` file in the specified path or its ancestors.","error":"Error: No package file found starting from /path/to/project"},{"fix":"Confirm that a lock file generated by a package manager (npm, yarn, pnpm, bun, deno) exists in your project. Check the starting path provided to `resolveLockFile` to ensure it's correct.","cause":"The `resolveLockFile` utility failed to find any known lock file (`yarn.lock`, `package-lock.json`, etc.) in the given directory or its ancestors.","error":"Error: No lock file found starting from /path/to/project"}],"ecosystem":"npm"}