Passa al contenuto principale
Versione: Prossimo

.pnpmfile.mjs

pnpm ti consente di agganciarti direttamente al processo di installazione tramite funzioni speciali (hook). 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.

Hooks

TL;DR

Funzione hookProcessoUtilizzi
hooks.readPackage(pkg, context): pkgChiamato dopo che pnpm ha analizzato il manifesto del pacchetto della dipendenzaTi permette di mutare il package.json di una dipendenza
hooks.afterAllResolved(lockfile, context): lockfileChiamato dopo che le dipendenze sono state risolte.Consente di modificare il file di blocco.
hooks.beforePacking(pkg): pkgCalled before creating a tarball during pack/publishAllows you to customize the published package.json

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

Consente di modificare package.json di una dipendenza dopo l'analisi e prima della risoluzione. Queste mutazioni non vengono salvate nel filesystem, tuttavia, interessano ciò viene risolto nel file di blocco e quindi ciò che viene installato.

Nota che dovrai eliminare pnpm-lock.yaml se hai già risolto la dipendenza che desideri modificare.

tip

If you need changes to package.json saved to the filesystem, you need to use the pnpm patch command and patch the package.json file. Questo potrebbe essere utile se vuoi rimuovere il campo bin di una dipendenza, ad esempio.

Argomenti

  • pkg - Il manifesto del pacchetto. La risposta dal registro o il contenuto di package.json.
  • contesto - Oggetto contesto per il passaggio. Il metodo #log(msg) consente di utilizzare un registro di debug per il passaggio.

Utilizzo

Example .pnpmfile.mjs (changes the dependencies of a dependency):

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
}

Limitazioni conosciute

Rimozione del campo scripts da una dipendenza del manifesto tramite readPackage sarà impedirà a pnpm di costruire la dipendenza. Quando si crea una dipendenza, pnpm legge il package.json del pacchetto dall'archivio del pacchetto, che non è interessato dall'hook. In order to ignore a package's build, use the allowBuilds field.

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

Added in: v10.8.0

Allows you to modify the configuration settings used by pnpm. This hook is most useful when paired with configDependencies, allowing you to share and reuse settings across different Git repositories.

For example, @pnpm/plugin-better-defaults uses the updateConfig hook to apply a curated set of recommended settings.

Esempio di utilizzo

.pnpmfile.mjs
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>

Consente di modificare l'output del file di blocco prima che venga serializzato.

Argomenti

  • lockfile - L'oggetto risoluzioni lockfile serializzato su pnpm-lock.yaml.
  • contesto - Oggetto contesto per il passaggio. Il metodo #log(msg) consente di utilizzare un registro di debug per il passaggio.

Esempio di utilizzo

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

export const hooks = {
afterAllResolved
}

Limitazioni note

Non ce ne sono: tutto ciò che può essere fatto con il file di blocco può essere modificato tramite questa funzione e puoi persino estendere la funzionalità del file di blocco.

hooks.beforePacking(pkg): pkg | Promise<pkg>

Added in: v10.28.0

Allows you to modify the package.json manifest before it is packed into a tarball during pnpm pack or pnpm publish. This is useful for customizing the published package without affecting your local development package.json.

Unlike hooks.readPackage, which modifies how dependencies are resolved during installation, beforePacking only affects the contents of the tarball that gets published.

Argomenti

  • pkg - The package manifest object that will be included in the published tarball.

Esempio di utilizzo

.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
}
note

The modifications made by this hook only affect the package.json inside the tarball. Your local package.json file remains unchanged.

hooks.preResolution(options): Promise<void>

This hook is executed after reading and parsing the lockfiles of the project, but before resolving dependencies. It allows modifications to the lockfile objects.

Argomenti

  • options.existsCurrentLockfile - A boolean that is true if the lockfile at node_modules/.pnpm/lock.yaml exists.
  • options.currentLockfile - The lockfile object from node_modules/.pnpm/lock.yaml.
  • options.existsNonEmptyWantedLockfile - A boolean that is true if the lockfile at pnpm-lock.yaml exists.
  • options.wantedLockfile - The lockfile object from pnpm-lock.yaml.
  • options.lockfileDir - The directory where the wanted lockfile is found.
  • options.storeDir - The location of the store directory.
  • options.registries - A map of scopes to registry URLs.

hooks.importPackage(destinationDir, options): Promise<string | undefined>

This hook allows to change how packages are written to node_modules. The return value is optional and states what method was used for importing the dependency, e.g.: clone, hardlink.

Argomenti

  • destinationDir - The destination directory where the package should be written.
  • options.disableRelinkLocalDirDeps
  • options.filesMap
  • options.force
  • options.resolvedFrom
  • options.keepModulesDir

Finders

Added in: v10.16.0

Finder functions are used with pnpm list and pnpm why via the --find-by flag.

Esempio:

.pnpmfile.mjs
export const finders = {
react17: (ctx) => {
return ctx.readManifest().peerDependencies?.react === "^17.0.0"
}
}

Utilizzo:

pnpm why --find-by=react17

See Finders for more details.

Configurazione correlata

ignorePnpmfile

  • Predefinito: false
  • Tipo: Booleano

The pnpmfile will be ignored. Utile insieme a --ignore-script quando si si desidera assicurarsi che nessuno script venga eseguito durante l'installazione.

pnpmfile

  • Default: ['.pnpmfile.mjs']
  • Type: path[]
  • Example: ['.pnpm/.pnpmfile.mjs']

The location of the local pnpmfile(s).

globalPnpmfile

  • Default: null
  • Tipo: percorso
  • Example: ~/.pnpm/global_pnpmfile.mjs

La posizione di un file pnpm globale. Un file pnpm globale viene utilizzato da tutti i progetti durante l'installazione.

note

Si consiglia di utilizzare file pnpm locali. Usa un pnpmfile globale solo se usi pnpm su progetti che non usano pnpm come gestore di pacchetti principale.