Package and TypeScript Configuration Utilities
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.
Common errors
-
ReferenceError: require is not defined in ES module scope
cause Attempting to use `require()` to import `pkg-types` in an environment where it's treated as an ES module.fixReplace `const { ... } = require('pkg-types')` with `import { ... } from 'pkg-types'`. Ensure your Node.js environment or build setup correctly handles ES modules. -
Error: No package file found starting from /path/to/project
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.fixVerify 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. -
Error: No lock file found starting from /path/to/project
cause The `resolveLockFile` utility failed to find any known lock file (`yarn.lock`, `package-lock.json`, etc.) in the given directory or its ancestors.fixConfirm 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.
Warnings
- breaking 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.
- gotcha 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.
- gotcha `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.
- gotcha `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.
Install
-
npm install pkg-types -
yarn add pkg-types -
pnpm add pkg-types
Imports
- readPackage
const readPackage = require('pkg-types')import { readPackage } from 'pkg-types' - PackageJson
import { PackageJson } from 'pkg-types'import type { PackageJson } from 'pkg-types' - readTSConfig
import readTSConfig from 'pkg-types'
import { readTSConfig } from 'pkg-types' - findWorkspaceDir
import { findWorkspaceDir } from 'pkg-types'
Quickstart
import { readPackage, findPackage, readTSConfig, findWorkspaceDir } from 'pkg-types';
import path from 'node:path';
async function getProjectConfig() {
try {
// Find the nearest package.json, package.json5, or package.yaml
const packageFile = await findPackage(process.cwd());
if (packageFile) {
console.log(`Found package file: ${packageFile}`);
// Read the package configuration, automatically detecting format
const pkg = await readPackage(path.dirname(packageFile));
console.log('Project Name:', pkg.name);
console.log('Project Version:', pkg.version);
} else {
console.log('No package file found in current directory or ancestors.');
}
// Read the nearest tsconfig.json
const tsconfigPath = await findPackage(process.cwd(), { filenames: ['tsconfig.json'] });
if (tsconfigPath) {
const tsconfig = await readTSConfig(path.dirname(tsconfigPath));
console.log('TSConfig Compiler Options:', tsconfig?.compilerOptions);
} else {
console.log('No tsconfig.json found.');
}
// Find the workspace root directory
const workspaceRoot = await findWorkspaceDir(process.cwd());
if (workspaceRoot) {
console.log('Detected workspace root:', workspaceRoot);
} else {
console.log('No workspace root detected.');
}
} catch (error) {
console.error('Failed to read project configuration:', (error as Error).message);
}
}
getProjectConfig();