.pnpmfile.mjs

pnpm дозволяє вам підключатися безпосередньо до процесу встановлення за допомогою спеціальних функцій (хуків). Hooks can be declared in a file called .pnpmfile.mjs (ESM) or .pnpmfile.cjs (CommonJS).

Стандартно .pnpmfile.mjs має бути розташований у тій же теці, що і файл блокування. Наприклад, у робочому просторі зі спільним файлом блокування .pnpmfile.mjs має бути в корені монорепо. In a workspace where each project has its own lockfile (sharedWorkspaceLockfile: false), each project runs the hooks of the pnpmfile in its own directory, then those of the pnpmfile in the root of the monorepo.

Хуки#

TL;DR#

Функція хука Процес Використання
hooks.readPackage(pkg, context): pkg Викликається після того, як pnpm проаналізує маніфест пакунків залежності Allows you to mutate a dependency's package.json.
hooks.updateConfig(config): config Called after pnpm reads its configuration Allows you to change pnpm's settings.
hooks.preResolution(options, logger) Called before the dependencies are resolved Allows you to mutate the lockfiles before resolution.
hooks.afterAllResolved(lockfile, context): lockfile Викликається після розвʼязання залежностей. Дозволяє змінювати файл блокування.
hooks.beforePacking(pkg, dir, context): pkg Викликається перед створенням tar-архіву під час пакування/публікації Дозволяє налаштувати опублікований package.json
resolvers Викликається під час виконання резолюції пакунка. Дозволяє реєструвати власні резолвери пакунків.
fetchers Викликається під час отримання пакунка. Дозволяє реєструвати власні фетчери пакунків.
finders Called by pnpm list and pnpm why with --find-by. Allows you to register custom package filters.

hooks.readPackage(pkg, context): pkg | Promise<pkg>#

Allows you to mutate a dependency's package.json after parsing and before resolution. Ці мутації не зберігаються у файловій системі, проте вони впливають на те, що буде отримано у файлі блокування, а отже, і на те, що буде встановлено.

pnpm records a checksum of the pnpmfile in the lockfile. When the pnpmfile changes, pnpm resolves the affected dependencies again.

підказка

Якщо вам потрібно внести зміни до package.json, збереженого у файловій системі, вам потрібно скористатися командою pnpm patch і виправити файл package.json. Це може бути корисно, наприклад, якщо ви хочете видалити поле bin у залежності.

Аргументи#

  • pkg — маніфест пакунка. Або відповідь з реєстру, або вміст package.json.
  • context — обʼєкт Context для кроку. Метод #log(msg) дозволяє використовувати журнал налагодження для кроку.

Використання#

Приклад .pnpmfile.mjs (змінює dependencies залежності):

.pnpmfile.mjs
function readPackage(pkg, context) {
  // Override the manifest of foo@1.x after downloading it from the registry
  if (pkg.name === 'foo' && pkg.version?.startsWith('1.')) {
    // Replace bar@x.x.x with bar@2.0.0
    pkg.dependencies = {
      ...pkg.dependencies,
      bar: '^2.0.0'
    }
    context.log('bar@1 => bar@2 in dependencies of foo')
  }

  // This will change any packages using baz@x.x.x to use baz@1.2.3
  if (pkg.dependencies?.baz) {
    pkg.dependencies.baz = '1.2.3';
  }

  return pkg
}

export const hooks = {
  readPackage
}

Відомі обмеження#

Видалення поля scripts з маніфесту залежності за допомогою readPackage не завадить pnpm зібрати залежність. При побудові залежності pnpm зчитує package.json пакунка з архіву пакунка, на який хук не впливає. To ignore a package's build, use the allowBuilds field.

hooks.updateConfig(config): config | Promise<config>#

Дозволяє змінювати параметри конфігурації, які використовуються pnpm. Цей хук є найбільш корисним у поєднанні з configDependencies, що дозволяє вам ділитися та повторно використовувати налаштування в різних репозиторіях Git.

Наприклад, @pnpm/plugin-better-defaults використовує хук updateConfig для застосування спеціального набору рекомендованих параметрів.

Приклад використання#

.pnpmfile.mjs
export const hooks = {
  updateConfig (config) {
    return Object.assign(config, {
      enablePrePostScripts: false,
      optimisticRepeatInstall: true,
      resolutionMode: 'lowest-direct',
      verifyDepsBeforeRun: 'install',
    })
  }
}

What the hook receives#

Since v12.4.1, config is the resolved configuration: every setting pnpm will act on, wherever it came from, including .npmrc, the command line, and the built-in defaults. A setting nobody set is absent from the object rather than present as null.

Two entries describe registry routing and credentials:

  • registriesByScope maps a scope (@acme, or default for the main registry) to the registry URL packages of that scope are fetched from. Rewriting the map redirects those fetches, except for the routes given on the command line.
  • configByUri maps a registry URI to its credentials.

Registry routing#

Returning registriesByScope replaces the routing map. Scopes omitted from the returned map use its default registry, or the previously configured main registry if default is omitted. The built-in @jsr route remains unless explicitly overridden. This hook changes the fallback registry:

.pnpmfile.mjs
export const hooks = {
  updateConfig (config) {
    return {
      ...config,
      registriesByScope: {
        default: 'https://registry.example.com/',
      },
    }
  },
}

To preserve existing scope routes while changing one route, spread ...config.registriesByScope into the returned map before the overrides.

A returned registries key is the registries setting, not the routing map. It merges per key with existing configuration. Returning registries: { default: ... } therefore changes the main registry but leaves scope routes from .npmrc in place.

Settings given on the command line#

Since v12.8.0, a setting given on the command line takes precedence over the hook. The hook still receives the command-line value, but pnpm puts it back after the hook returns, so changing it in the hook has no effect. This covers flags such as --registry, --config.@acme:registry, --store-dir, --state-dir, --config.<key> overrides, and setting flags such as --no-optional.

Which commands load the pnpmfile#

Since v12.3.0, pnpm run, pnpm exec, pnpm rebuild, the script shortcuts such as pnpm test, and pnpm link, pnpm outdated, pnpm import, pnpm pack, pnpm publish, and pnpm stage publish all load the pnpmfile before doing their work, so updateConfig settings such as extraEnv and extraBinPaths reach the processes they spawn and hook-provided catalogs resolve at pack time.

hooks.afterAllResolved(lockfile, context): lockfile | Promise<lockfile>#

Дозволяє змінювати вивід файлу блокування перед його серіалізацією.

Аргументи#

  • lockfile — Обʼєкт резолюції файлу блокування, який серіалізовано у pnpm-lock.yaml.
  • context — обʼєкт Context для кроку. Метод #log(msg) дозволяє використовувати журнал налагодження для кроку.

Приклад використання#

.pnpmfile.mjs
function afterAllResolved(lockfile, context) {
  // ...
  return lockfile
}

export const hooks = {
  afterAllResolved
}

Відомі обмеження#

Їх немає — все, що можна зробити з файлом блокування, можна змінити за допомогою цієї функції, і ви навіть можете розширити функціональність файлу блокування.

hooks.beforePacking(pkg, dir, context): pkg | Promise<pkg>#

Дозволяє змінити маніфест package.json перед його пакуванням у tar-архів під час pnpm pack або pnpm publish. Це корисно для налаштування опублікованого пакунка без впливу на вашу локальну розробку package.json.

На відміну від hooks.readPackage, який змінює спосіб розвʼязання залежностей під час встановлення, beforePacking впливає лише на вміст архіву, який публікується.

Аргументи#

  • pkg – Об’єкт маніфесту пакунка, який буде включено до опублікованого tar-архіву.
  • dir - The directory of the project being packed.
  • context — обʼєкт Context для кроку. Метод #log(msg) дозволяє використовувати журнал налагодження для кроку.

Приклад використання#

.pnpmfile.mjs
function beforePacking(pkg) {
  // Remove development-only fields from published package
  delete pkg.devDependencies
  delete pkg.scripts?.test

  // Add publication metadata
  pkg.publishedAt = new Date().toISOString()

  // Modify package exports for production
  if (pkg.name === 'my-package') {
    pkg.main = './dist/index.js'
  }

  return pkg
}

export const hooks = {
  beforePacking
}

нотатка

Зміни, зроблені цим хуком, впливають тільки на package.json всередині архіву. Ваш локальний файл package.json залишається незмінним.

hooks.preResolution(options, logger): Promise<void>#

Цей хук буде виконаний після читання та аналізу файлів блокування проєкту, але перед розвʼязанням залежностей. pnpm continues the install from the changes it makes to options.wantedLockfile and options.currentLockfile. With --frozen-lockfile, pnpm checks the changed wanted lockfile against the project manifests.

Only changes made to these objects in place count. pnpm ignores the hook's return value and any object assigned to an options field. A hook that throws fails the install, and so does a hook that leaves a lockfile object in a shape that is not a valid lockfile.

Аргументи#

  • options.existsCurrentLockfile — булеве значення, яке є істинним, якщо файл блокування за адресою node_modules/.pnpm/lock.yaml існує.
  • options.currentLockfile — Обʼєкт файлу блокування з node_modules/.pnpm/lock.yaml.
  • options.existsNonEmptyWantedLockfile — булеве значення, яке є істинним, якщо файл блокування за адресою pnpm-lock.yaml існує.
  • options.wantedLockfile — Обʼєкт файлу блокування з pnpm-lock.yaml.
  • options.lockfileDir — Тека, де знаходиться потрібний файл блокування.
  • options.storeDir — Розташування теки store.
  • options.registries — Зіставлення областей видимості з URL-адресами реєстрів.
  • logger.info(msg) and logger.warn(msg) - Print a message from the hook at the info or warning level.

Приклад використання#

.pnpmfile.mjs
function preResolution({ wantedLockfile }, logger) {
  // Resolve the dependencies of the root project again
  if (wantedLockfile.importers?.['.']) {
    delete wantedLockfile.importers['.']
    logger.info('Dropped the locked dependencies of the root project')
  }
}

export const hooks = {
  preResolution
}

hooks.importPackage(destinationDir, options)#

Removed in v12.0.0

pnpm ignores the importPackage hook and warns when a pnpmfile defines it. Use the packageImportMethod setting to choose how packages are written to node_modules. If you rely on this hook, comment on #14101.

hooks.filterLog(log): boolean#

Deprecated in v12.0.0

filterLog returns false for a log entry to keep it out of pnpm's reporter output. pnpm 12 ignores the hook and warns when a pnpmfile defines it, so remove it rather than relying on it. Use loglevel to choose how much pnpm reports.

hooks.fetchers#

Видалено в v11.0.0

hooks.fetchers has been removed. Use top-level fetchers instead. See the Custom Fetchers section for the new API.

Пошук#

A pnpmfile can export finders, functions that pnpm list and pnpm why use with the --find-by flag. See Finders.

Custom resolvers and fetchers#

Custom resolvers and fetchers allow you to implement custom package resolution and fetching logic for new package identifier schemes (like my-protocol:package-name). They are registered as top-level exports in .pnpmfile.cjs:

.pnpmfile.cjs
module.exports = {
  resolvers: [customResolver1, customResolver2],
  fetchers: [customFetcher1, customFetcher2],
}

TypeScript interfaces#

interface CustomResolver {
  canResolve?: (wantedDependency: WantedDependency) => boolean | Promise<boolean>
  resolve?: (wantedDependency: WantedDependency, opts: ResolveOptions) => ResolveResult | Promise<ResolveResult>
  shouldRefreshResolution?: (depPath: string, pkgSnapshot: PackageSnapshot) => boolean | Promise<boolean>
}

interface CustomFetcher {
  canFetch?: (pkgId: string, resolution: Resolution) => boolean | Promise<boolean>
  fetch?: (cafs: Cafs, resolution: Resolution, opts: FetchOptions, fetchers: Fetchers) => FetchResult | Promise<FetchResult>
}

Custom resolvers#

Custom resolvers convert package descriptors (e.g., foo@^1.0.0) into resolutions that are stored in the lockfile.

Resolver interface#

Власний резолвер — це об’єкт, який може реалізовувати будь-яку комбінацію таких методів:

canResolve(wantedDependency): boolean | Promise<boolean>#

Визначає, чи може цей резолвер розвʼязати задану залежність.

Arguments:

  • wantedDependency - Object with:
    • alias - The package name or alias as it appears in package.json
    • bareSpecifier - The version range, git URL, file path, or other specifier

Returns: true if this resolver can handle the package, false otherwise. This determines whether resolve will be called.

resolve(wantedDependency, opts): ResolveResult | Promise<ResolveResult>#

Визначає необхідну залежність від конкретних метаданих пакунка та інформації про її визначення.

Arguments:

  • wantedDependency - The wanted dependency (same as canResolve)
  • opts - Object with:
    • lockfileDir - Directory containing the lockfile
    • projectDir - The project root directory
    • preferredVersions - Map of package names to preferred versions

Returns: Object with:

  • id - Unique package identifier (e.g., 'custom-pkg@1.0.0')
  • resolution - Resolution metadata. Це можуть бути:
    • Standard resolution, e.g. { tarball: 'https://...', integrity: '...' }
    • Custom resolution: { type: 'custom:cdn', url: '...' }

Власні резолюції можуть оброблятись відпвоідним власним фетчером.

Custom Resolution Types

Custom resolutions must use the custom: prefix in their type field (e.g., custom:cdn, custom:artifactory) to differentiate them from pnpm's built-in resolution types.

shouldRefreshResolution(depPath, pkgSnapshot): boolean | Promise<boolean>#

Return true to trigger full resolution of all packages, skipping the "Lockfile is up to date" optimization. Це є корисним для реалізації інвалідування кешу на основі часу або іншої власної логіки повторного визначення резолюцій.

Arguments:

  • depPath - The package identifier string (e.g., lodash@4.17.21)
  • pkgSnapshot - The lockfile entry for this package, providing direct access to the resolution, dependencies, etc.

Returns: true to force re-resolution, false otherwise.

нотатка

shouldRefreshResolution is skipped during frozen lockfile installs, as no resolution is allowed in that mode.

Custom fetchers#

Власні фетчери повністю відповідають за завантаження власних типів пакунків, завантажуючи вміст пакунків із власних джерел та зберігаючи його у файловій системі pnpm з адресацією за вмістом.

Fetcher interface#

Власний фетчер — це об’єкт, який може впроваджувати наступні методи:

canFetch(pkgId, resolution): boolean | Promise<boolean>#

Визначає, чи може цей фетчер отримати пакунок з вказаною резолюцією.

Arguments:

  • pkgId - The unique package identifier from the resolution phase
  • resolution - The resolution object from a resolver's resolve method

Returns: true if this fetcher can handle fetching this package, false otherwise.

fetch(cafs, resolution, opts, fetchers): FetchResult | CustomFetcherDelegation | Promise<FetchResult | CustomFetcherDelegation>#

Отримує файли пакунка та повертає метадані отриманого пакунка.

Arguments:

  • cafs - Content-addressable file system interface for storing files
  • resolution - The resolution object (same as passed to canFetch)
  • opts - Fetch options including:
    • lockfileDir - Directory containing the lockfile
    • filesIndexFile - Path for the files index
    • onStart - Optional callback when fetch starts
    • onProgress - Optional progress callback
  • fetchers - Object containing pnpm's standard fetchers for delegation:
    • remoteTarball - Fetcher for remote tarballs
    • localTarball - Fetcher for local tarballs
    • gitHostedTarball - Fetcher for GitHub/GitLab/Bitbucket tarballs.
    • directory - Fetcher for local directories. It rejects with ERR_PNPM_TARBALL_INTEGRITY if the lockfile pins an archive integrity for the package.
    • git - Fetcher for git repositories.
    • binary - Fetcher for runtime archives, such as Node.js.

A fetch result that came from a built-in fetcher must be returned unchanged. pnpm rejects a result whose filesMap gained, lost, or changed a file, and it ignores a changed manifest or requiresBuild. To install different files, return a { delegate } envelope instead.

Returns: either a fetch result, or a delegation envelope.

A fetch result is an object with:

  • filesIndex - Map of relative file paths to their physical locations. Для віддалених пакунків це шляхи у сховищі pnpm з адресацією за вмістом (CAFS, content-addressable store). For local packages (when local: true), these are absolute paths to files on disk.
  • manifest - Optional. Файл package.json з отриманого пакунка. Якщо не вказано, pnpm прочитає його з диску за потреби. Це дозволяє уникнути додаткової операції вводу-виводу і рекомендується, якщо дані маніфесту вже доступні (наприклад, якщо вони були проаналізовані під час отримання).
  • requiresBuild - Boolean indicating whether the package has build scripts that need to be executed. Set to true if the package has preinstall, install, or postinstall scripts, or contains binding.gyp or .hooks/ files. Стандартні фетчери визначають це автоматично на основі маніфесту та списку файлів.
  • local - Optional. Set to true to load the package directly from disk without copying to pnpm's store. When true, filesIndex should contain absolute paths to files on disk, and pnpm will hardlink them to node_modules instead of copying. This is how the directory fetcher handles local dependencies (e.g., file:../my-package).

Delegating to the built-in fetchers#

Rather than fetching the package itself, a custom fetcher may hand the work back to pnpm. There are two ways to do this.

Return a { delegate } envelope. Instead of a fetch result, return an object with a single delegate key holding the resolution pnpm should fetch instead. pnpm rewrites the package's resolution to that shape and runs its built-in fetch path on it:

.pnpmfile.cjs
const customFetcher = {
  canFetch: (pkgId, resolution) => resolution.type === 'custom:url',
  fetch: (cafs, resolution) => ({
    delegate: {
      tarball: resolution.customUrl,
      integrity: resolution.integrity,
    },
  }),
}

module.exports = { fetchers: [customFetcher] }

The delegated resolution must be a complete, fetchable shape (for example { tarball, integrity }). Delegation is single-step: a delegate that is itself custom-typed is rejected.

Call fetchers.* directly. The fetchers argument gives you pnpm's standard fetchers, so you can transform the resolution and invoke one yourself.

Prefer the envelope for portability

The { delegate } envelope works for every resolution in every pnpm version. In pnpm 12, cafs is a handle to pass to the built-in fetchers, with the store's storeDir and a tempDir() method. fetchers provides localTarball, remoteTarball, gitHostedTarball, git, binary, and directory.

Приклад використання#

Basic custom resolver#

У цьому прикладі показано власний резолвер, який розпізнає пакунки з власного реєстру:

.pnpmfile.cjs
const customResolver = {
  // Only handle packages with @company scope
  canResolve: (wantedDependency) => {
    return wantedDependency.alias.startsWith('@company/')
  },

  resolve: async (wantedDependency, opts) => {
    // Fetch metadata from custom registry
    const response = await fetch(
      `https://custom-registry.company.com/${wantedDependency.alias}/${wantedDependency.bareSpecifier}`
    )
    const metadata = await response.json()

    return {
      id: `${metadata.name}@${metadata.version}`,
      resolution: {
        tarball: metadata.tarballUrl,
        integrity: metadata.integrity
      }
    }
  }
}

module.exports = {
  resolvers: [customResolver]
}
Custom resolver and fetcher with shouldRefreshResolution#

У цьому прикладі показано, як резолвер і фетчер працюють разом із власним типом резолюції та інвалідуванням кешу за часом:

.pnpmfile.cjs
const customResolver = {
  canResolve: (wantedDependency) => {
    return wantedDependency.alias.startsWith('company-cdn:')
  },

  resolve: async (wantedDependency, opts) => {
    const actualName = wantedDependency.alias.replace('company-cdn:', '')
    const version = await fetchVersionFromCompanyCDN(actualName, wantedDependency.bareSpecifier)

    return {
      id: `company-cdn:${actualName}@${version}`,
      resolution: {
        type: 'custom:cdn',
        cdnUrl: `https://cdn.company.com/packages/${actualName}/${version}.tgz`,
        cachedAt: Date.now(), // Custom metadata for shouldRefreshResolution
      },
    }
  },

  shouldRefreshResolution: (depPath, pkgSnapshot) => {
    // Check custom metadata stored in the resolution
    const cachedAt = pkgSnapshot.resolution?.cachedAt
    if (cachedAt && Date.now() - cachedAt > 24 * 60 * 60 * 1000) {
      return true // Re-resolve if cached more than 24 hours ago
    }
    return false
  },
}

const customFetcher = {
  canFetch: (pkgId, resolution) => {
    return resolution.type === 'custom:cdn'
  },

  fetch: async (cafs, resolution, opts, fetchers) => {
    // Delegate to pnpm's standard tarball fetcher
    const tarballResolution = {
      tarball: resolution.cdnUrl,
      integrity: resolution.integrity,
    }

    return fetchers.remoteTarball(cafs, tarballResolution, opts)
  },
}

module.exports = {
  resolvers: [customResolver],
  fetchers: [customFetcher],
}
Basic custom fetcher#

У цьому прикладі показано власний фетчер, який завантажує певні пакунки з іншого джерела:

.pnpmfile.cjs
const customFetcher = {
  canFetch: (pkgId, resolution) => {
    return pkgId.startsWith('@company/')
  },

  fetch: async (cafs, resolution, opts, fetchers) => {
    // Delegate to pnpm's tarball fetcher with modified URL
    const tarballResolution = {
      tarball: resolution.tarball.replace(
        'https://registry.npmjs.org/',
        'https://custom-registry.company.com/'
      ),
      integrity: resolution.integrity
    }

    return fetchers.remoteTarball(cafs, tarballResolution, opts)
  }
}

module.exports = {
  fetchers: [customFetcher]
}
Custom resolution type with resolver and fetcher#

У цьому прикладі показано, як власний резолвер і фетчер працюють разом із власним типом резолюції:

.pnpmfile.cjs
const customResolver = {
  canResolve: (wantedDependency) => {
    return wantedDependency.alias.startsWith('@internal/')
  },

  resolve: async (wantedDependency) => {
    return {
      id: `${wantedDependency.alias}@${wantedDependency.bareSpecifier}`,
      resolution: {
        type: 'custom:internal-directory',
        directory: `/packages/${wantedDependency.alias}/${wantedDependency.bareSpecifier}`
      }
    }
  }
}

const customFetcher = {
  canFetch: (pkgId, resolution) => {
    return resolution.type === 'custom:internal-directory'
  },

  fetch: async (cafs, resolution, opts, fetchers) => {
    // Delegate to pnpm's directory fetcher for local packages
    const directoryResolution = {
      type: 'directory',
      directory: resolution.directory
    }

    return fetchers.directory(cafs, directoryResolution, opts)
  }
}

module.exports = {
  resolvers: [customResolver],
  fetchers: [customFetcher]
}

Priority and ordering#

Коли зареєстровано кілька резолверів, вони перевіряються по порядку. The first resolver where canResolve returns true will be used for resolution. The same applies for fetchers: The first fetcher where canFetch returns true will be used during the fetch phase.

Спочатку перевіряються власні резолвери, а вже потім — вбудовані резолвери pnpm (npm, git, tarball тощо), що дає вам повний контроль над пошуком пакунків.

Performance considerations#

canResolve(), canFetch(), and shouldRefreshResolution() should be cheap checks (ideally synchronous), as they're called for every dependency during resolution.

ignorePnpmfile#

  • Стандартно: false
  • Тип: Boolean

Файл pnpmfile буде проігноровано. Корисно використовувати разом з --ignore-scripts, якщо ви хочете переконатися, що жоден скрипт не буде виконано під час встановлення.

pnpmfile#

  • Default: ['.pnpmfile.mjs'], or ['.pnpmfile.cjs'] if there is no .pnpmfile.mjs
  • Тип: path[]
  • Приклад: ['.pnpm/.pnpmfile.mjs']

The location of the local pnpmfiles.

globalPnpmfile#

  • Стандартно: null
  • Тип: path
  • Example: ~/.pnpm/global_pnpmfile.mjs

Розташування глобального pnpmfile. Глобальний pnpmfile використовується всіма проєктами під час встановлення.

нотатка

Рекомендується використовувати локальні pnpmfiles. Використовуйте глобальний файл pnpmfile лише у тому випадку, якщо ви використовуєте pnpm у проєктах, які не використовують pnpm як основний менеджер пакунків.