.pnpmfile.mjs
pnpm lets you hook directly into the installation process via special functions (hooks). 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
| Hook Function | Processus | Uses |
|---|---|---|
hooks.readPackage(pkg, context): pkg | Appelé après que pnpm ait analysé le manifeste du paquet de la dépendance | Permet de modifier le package.json d’une dépendance |
hooks.afterAllResolved(lockfile, context): lockfile | Appelé après que les dépendances aient été résolues. | Permet de modifier le fichier lockfile |
hooks.beforePacking(pkg): pkg | Called before creating a tarball during pack/publish | Allows you to customize the published package.json |
hooks.readPackage(pkg, context): pkg | Promise<pkg>
Permet de modifier le package.json d’une dépendance après l’analyse et avant la résolution. Ces mutations ne sont pas enregistrées dans le système de fichiers, cependant, elles affecteront ce qui est résolu dans le fichier lockfile et donc ce qui est installé.
Notez que vous devrez supprimer le pnpm-lock.yaml si vous avez déjà résolu la dépendance que vous souhaitez modifier.
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. Cela peut être utile si vous souhaitez supprimer le champs bin d'une dépendance par exemple.
Arguments
pkg- Le manifeste du package. Soit la réponse du registre, soit le contenu depackage.json.context- Objet de contexte pour l'étape. La méthode#log(msg)permet d'utiliser un journal de débogage pour l'étape.
Utilisation
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
}
Limitations connues
Supprimer le champ scripts du manifeste d'une dépendance via readPackage n'empêchera pas de construire la dépendance. Lors de la construction d'une dépendance, pnpm lit le package.json du package à partir de l'archive du package, qui n'est pas affectée par le 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.
Exemple d'utilisation
export const hooks = {
updateConfig (config) {
return Object.assign(config, {
enablePrePostScripts: false,
optimisticRepeatInstall: true,
resolutionMode: 'lowest-direct',
verifyDepsBeforeRun: 'install',
})
}
}
hooks.afterAllResolved(lockfile, context): lockfile | Promesse<lockfile>
Vous permet de modifier la sortie du fichier de verrouillage avant qu’elle ne soit sérialisée.
Arguments
lockfile- Le fichier de résolution lockfile sérialisé danspnpm-lock.yaml.context- Objet de contexte pour l'étape. La méthode#log(msg)permet d'utiliser un journal de débogage pour l'étape.
Exemple d'utilisation
function afterAllResolved(lockfile, context) {
// ...
return lockfile
}
export const hooks = {
afterAllResolved
}
Limitations connues
Il n'y en a pas - tout ce qui peut être fait avec le fichier de verrouillage peut être via cette fonction, et vous pouvez même étendre les fonctionnalités du fichier de verrouillage.
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.
Arguments
pkg- The package manifest object that will be included in the published tarball.
Exemple d'utilisation
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
}
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.
Arguments
options.existsCurrentLockfile- A boolean that is true if the lockfile atnode_modules/.pnpm/lock.yamlexists.options.currentLockfile- The lockfile object fromnode_modules/.pnpm/lock.yaml.options.existsNonEmptyWantedLockfile- A boolean that is true if the lockfile atpnpm-lock.yamlexists.options.wantedLockfile- The lockfile object frompnpm-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.
Arguments
destinationDir- The destination directory where the package should be written.options.disableRelinkLocalDirDepsoptions.filesMapoptions.forceoptions.resolvedFromoptions.keepModulesDir
Finders
Added in: v10.16.0
Finder functions are used with pnpm list and pnpm why via the --find-by flag.
Exemple:
export const finders = {
react17: (ctx) => {
return ctx.readManifest().peerDependencies?.react === "^17.0.0"
}
}
Utilisation :
pnpm why --find-by=react17
See Finders for more details.
Configuration associée
ignorePnpmfile
- Default: false
- Type: Boolean
The pnpmfile will be ignored. Utile avec --ignore-scripts lorsque vous voulez vous assurer qu'aucun script n'est exécuté pendant l'installation.
pnpmfile
- Default: ['.pnpmfile.mjs']
- Type: path[]
- Example: ['.pnpm/.pnpmfile.mjs']
The location of the local pnpmfile(s).
globalPnpmfile
- Default: null
- Type: chemin
- Example: ~/.pnpm/global_pnpmfile.mjs
L'emplacement du pnpmfile global. Un fichier pnpm global est utilisé par tous les projets lors de l'installation.
Il est recommandé d'utiliser les fichiers pnpmfiles locaux. N'utilisez un pnpmfile global que si vous utilisez pnpm sur des projets qui n'utilisent pas pnpm comme gestionnaire de packages principal.