.pnpmfile.mjs
pnpm дозволяє вам підключатися безпосередньо до процесу встановлення за допомогою спеціальних функцій (хуків). Hooks can be declared in a file called .pnpmfile.mjs (ESM) or .pnpmfile.cjs (CommonJS).
By default, .pnpmfile.mjs should be located in the same directory as the lockfile. For instance, in a workspace with a shared lockfile, .pnpmfile.mjs should be in the root of the monorepo.
Хуки
TL;DR
| Функція хука | Процес | Використання |
|---|---|---|
hooks.readPackage(pkg, context): pkg | Викликається після того, як pnpm проаналізує маніфест пакунків залежності | Allows you to mutate a dependency's package.json. |
hooks.afterAllResolved(lockfile, context): lockfile | Викликається після розвʼязання залежностей. | Дозволяє змінювати файл блокування. |
hooks.beforePacking(pkg): pkg | Викликається перед створенням tar-архіву під час пакування/публікації | Дозволяє налаштувати опублікований package.json |
resolvers | Called during package resolution. | Allows you to register custom package resolvers. |
fetchers | Called during package fetching. | Allows you to register custom package fetchers. |
hooks.readPackage(pkg, context): pkg | Promise<pkg>
Дозволяє змінювати package.json залежності після аналізу і до розвʼязання. Ці мутації не зберігаються у файловій системі, проте вони впливають на те, що буде отримано у файлі блокування, а отже, і на те, що буде встановлено.
Зауважте, що вам потрібно буде видалити pnpm-lock.yaml, якщо ви вже розвʼязали залежність, яку ви хочете змінити.
Якщо вам потрібно внести зміни до package.json, збереженого у файловій системі, вам потрібно скористатися командою pnpm patch і виправити файл package.json. Це може бути корисно, наприклад, якщо ви хочете видалити поле bin у залежності.
Аргументи
pkg– маніфест пакунка. Або відповідь з реєстру, або вмістpackage.json.context— обʼєкт Context для кроку. Метод#log(msg)дозволяє використовувати журнал налагодження для кроку.
Використання
Example .pnpmfile.mjs (changes the dependencies of a dependency):
function readPackage(pkg, context) {
// Перевизначимо маніфест foo@1.x, завантаживши його з реєстру
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 пакунка з архіву пакунка, на який хук не впливає. In order to ignore a package's build, use the allowBuilds field.
hooks.updateConfig(config): config | Promise<config>
Додано у: v10.8.0
Дозволяє змінювати параметри конфігурації, які використовуються pnpm. Цей хук є найбільш корисним у поєднанні з configDependencies, що дозволяє вам ділитися та повторно використовувати налаштування в різних репозиторіях Git.
Наприклад, @pnpm/plugin-better-defaults використовує хук updateConfig для застосування спеціального набору рекомендованих параметрів.
Приклад використання
export const hooks = {
updateConfig (config) {
return Object.assign(config, {
enablePrePostScripts: false,
optimisticRepeatInstall: true,
resolutionMode: 'lowest-direct',
verifyDepsBeforeRun: 'install',
})
}
}
hooks.afterAllResolved(lockfile, context): lockfile | Promise<lockfile>
Дозволяє змінювати вивід файлу блокування перед його серіалізацією.
Аргументи
lockfile— Обʼєкт резолюції файлу блокування, який серіалізовано уpnpm-lock.yaml.context— обʼєкт Context для кроку. Метод#log(msg)дозволяє використовувати журнал налагодження для кроку.
Приклад використання
function afterAllResolved(lockfile, context) {
// ...
return lockfile
}
export const hooks = {
afterAllResolved
}
Відомі обмеження
Їх немає — все, що можна зробити з файлом блокування, можна змінити за допомогою цієї функції, і ви навіть можете розширити функціональність файлу блокування.
hooks.beforePacking(pkg): pkg | Promise<pkg>
Додано у: v10.28.0
Дозволяє змінити маніфест package.json перед його пакуванням у tar-архів під час pnpm pack або pnpm publish. Це корисно для налаштування опублікованого пакунка без впливу на вашу локальну розробку package.json.
На відміну від hooks.readPackage, який змінює спосіб розвʼязання залежностей під час встановлення, beforePacking впливає лише на вміст архіву, який публікується.
Аргументи
pkg– Об’єкт маніфесту пакунка, який буде включено до опублікованого tar-архіву.
Приклад використання
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): Promise<void>
Цей хук буде виконаний після читання та аналізу файлів блокування проєкту, але перед розвʼязанням залежностей. Це дозволяє змінювати обʼєкти файлу блокування.
Аргументи
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-адресами реєстрів.
hooks.importPackage(destinationDir, options): Promise<string | undefined>
Цей хук дозволяє змінити спосіб запису пакунків до node_modules. Значення, що повертається, є необовʼязковим і вказує, який метод було використано для імпорту залежності, наприклад: clone, hardlink.
Аргументи
destinationDir— Тека призначення, куди має бути записано пакунок.options.disableRelinkLocalDirDepsoptions.filesMapoptions.forceoptions.resolvedFromoptions.keepModulesDir
hooks.fetchers
hooks.fetchers has been removed. Use top-level fetchers instead. See the Custom Fetchers section for the new API.
Пошук
Додано у: v10.16.0
Функції пошуку використовуються з pnpm list та pnpm why через прапорець --find-by.
Приклад:
export const finders = {
react17: (ctx) => {
return ctx.readManifest().peerDependencies?.react === "^17.0.0"
}
}
Використання:
pnpm why --find-by=react17
Дивіться Пошук для отримання додаткової інформації.
Custom Resolvers and Fetchers
Added in: v11.0.0
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:
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
A custom resolver is an object that can implement any combination of the following methods:
canResolve(wantedDependency): boolean | Promise<boolean>
Determines whether this resolver can resolve a given wanted dependency.
Arguments:
wantedDependency- Object with:alias- The package name or alias as it appears in package.jsonbareSpecifier- 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>
Resolves a wanted dependency to specific package metadata and resolution information.
Arguments:
wantedDependency- The wanted dependency (same ascanResolve)opts- Object with:lockfileDir- Directory containing the lockfileprojectDir- The project root directorypreferredVersions- Map of package names to preferred versions
Returns: Object with:
id- Unique package identifier (e.g.,'custom-pkg@1.0.0')resolution- Resolution metadata. This can be:- Standard resolution, e.g.
{ tarball: 'https://...', integrity: '...' } - Custom resolution:
{ type: 'custom:cdn', url: '...' }
- Standard resolution, e.g.
Custom resolutions must be handled by a corresponding custom fetcher.
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. This is useful for implementing time-based cache invalidation or other custom re-resolution logic.
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
Custom fetchers completely handle fetching for custom package types, downloading package contents from custom sources and storing them in pnpm's content-addressable file system.
Fetcher Interface
A custom fetcher is an object that can implement the following methods:
canFetch(pkgId, resolution): boolean | Promise<boolean>
Determines whether this fetcher can fetch a package with the given resolution.
Arguments:
pkgId- The unique package identifier from the resolution phaseresolution- The resolution object from a resolver'sresolvemethod
Returns: true if this fetcher can handle fetching this package, false otherwise.
fetch(cafs, resolution, opts, fetchers): FetchResult | Promise<FetchResult>
Fetches package files and returns metadata about the fetched package.
Arguments:
cafs- Content-addressable file system interface for storing filesresolution- The resolution object (same as passed tocanFetch)opts- Fetch options including:lockfileDir- Directory containing the lockfilefilesIndexFile- Path for the files indexonStart- Optional callback when fetch startsonProgress- Optional progress callback
fetchers- Object containing pnpm's standard fetchers for delegation:remoteTarball- Fetcher for remote tarballslocalTarball- Fetcher for local tarballsgitHostedTarball- Fetcher for GitHub/GitLab/Bitbucket tarballsdirectory- Fetcher for local directoriesgit- Fetcher for git repositories
Returns: Object with:
filesIndex- Map of relative file paths to their physical locations. For remote packages, these are paths in pnpm's content-addressable store (CAFS). For local packages (whenlocal: true), these are absolute paths to files on disk.manifest- Optional. The package.json from the fetched package. If not provided, pnpm will read it from disk when needed. Providing it avoids an extra file I/O operation and is recommended when you have the manifest data readily available (e.g., already parsed during fetch).requiresBuild- Boolean indicating whether the package has build scripts that need to be executed. Set totrueif the package haspreinstall,install, orpostinstallscripts, or containsbinding.gypor.hooks/files. Standard fetchers determine this automatically using the manifest and file list.local- Optional. Set totrueto load the package directly from disk without copying to pnpm's store. Whentrue,filesIndexshould contain absolute paths to files on disk, and pnpm will hardlink them tonode_modulesinstead of copying. This is how the directory fetcher handles local dependencies (e.g.,file:../my-package).
Custom fetchers can delegate to pnpm's built-in fetchers using the fetchers parameter.
Usage Examples
Basic Custom Resolver
This example shows a custom resolver that resolves packages from a custom registry:
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
This example shows a resolver and fetcher working together with a custom resolution type and time-based cache invalidation:
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
This example shows a custom fetcher that fetches certain packages from a different source:
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
This example shows a custom resolver and fetcher working together with a custom resolution type:
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
When multiple resolvers are registered, they are checked in order. 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.
Custom resolvers are tried before pnpm's built-in resolvers (npm, git, tarball, etc.), giving you full control over package resolution.
Performance Considerations
canResolve(), canFetch(), and shouldRefreshResolution() should be cheap checks (ideally synchronous), as they're called for every dependency during resolution.
Повʼязана конфігурація
ignorePnpmfile
- Стандартно: false
- Тип: Boolean
The pnpmfile will be ignored. Корисно використовувати разом з --ignore-scripts, якщо ви хочете переконатися, що жоден скрипт не буде виконано під час встановлення.
pnpmfile
- Default: ['.pnpmfile.mjs']
- Тип: path[]
- Example: ['.pnpm/.pnpmfile.mjs']
Розташування локальних файлів pnpmfile.
globalPnpmfile
- Стандартно: null
- Тип: path
- Example: ~/.pnpm/global_pnpmfile.mjs
Розташування глобального pnpmfile. Глобальний pnpmfile використовується всіма проєктами під час встановлення.
Рекомендується використовувати локальні pnpmfiles. Використовуйте глобальний файл pnpmfile лише у тому випадку, якщо ви використовуєте pnpm у проєктах, які не використовують pnpm як основний менеджер пакунків.