Skip to content

Package directory resolution API #59918

@KJ7LNW

Description

@KJ7LNW

What is the problem this feature will solve?

Currently, resolving a package name to its directory requires:

  1. require.resolve(packageName) - needs "." export or main field
  2. Walking up from resolved entry point to find package.json

This is fragile for build tools that need package directories for scanning source files, especially with modern package.json exports restrictions.

Evidence: Node.js Already Knows the Path

When resolution fails, Node.js error messages reveal it already knows the package directory:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: 
No "exports" main defined in /path/to/project/packages/@scope/package-name/package.json 
imported from /path/to/project/src/file.css

The error shows Node.js found /path/to/project/packages/@scope/package-name/ but won't expose this path to user code without proper exports. This proves the resolution logic already exists internally.

What is the feature you are proposing to solve the problem?

Option 1: Extend require.resolve

// New parameter to resolve to directory containing package.json
const packageDir = require.resolve(packageName, { resolveToDirectory: true })

Option 2: New API

const packageDir = require.resolvePackageDirectory(packageName)
// or
const Module = require('module')
const packageDir = Module.resolvePackageDirectory(packageName, fromPath)

What alternatives have you considered?

Currently, resolving a package name to its directory requires:

  1. require.resolve(packageName) - needs "." export or main field
  2. Walking up from resolved entry point to find package.json

Use Cases

  • Build tools (Vite, webpack plugins) scanning package source files
  • Tailwind CSS content detection across monorepo packages
  • Dev tools that need to locate package assets/configs
  • Monorepo tooling that works with workspace packages

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.

    Type

    No type

    Projects

    Status

    Awaiting Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions