Skip to content

hookWorkflownode

Enforce Package Manager

A Claude Code hook that blocks npm and npx when the project has a pnpm, Yarn or Bun lockfile, and tells the agent which tool to use instead.

npx workspacetemplates add enforce-package-manager --tool claude-code

Writes 1 file to .claude/

.claude/settings.jsonmerge into your file16 lines · 903 BFile
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{let j={};try{j=JSON.parse(d)}catch(e){}const c=String((j.tool_input||{}).command||'')+' ';if(/(^|[;&|(][ ]*)(npm|npx)[ ]/.test(c)){const fs=require('fs'),p=require('path');const w=j.cwd||process.cwd();const has=n=>fs.existsSync(p.join(w,n));if(!has('package-lock.json')){const t=has('pnpm-lock.yaml')?['pnpm','pnpm dlx']:has('yarn.lock')?['yarn','yarn dlx']:(has('bun.lockb')||has('bun.lock'))?['bun','bunx']:null;if(t){console.error('This project uses '+t[0]+' (its lockfile is committed). Run the command with '+t[0]+' instead of npm, and use '+t[1]+' in place of npx.');process.exit(2)}}}process.exit(0)})\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

What it does

Running npm install in a pnpm repo creates a second lockfile and a node_modules tree nobody asked for. This PreToolUse hook reads each shell command and, when it starts with npm or npx, looks for the lockfile that shows which manager the project uses.

A pnpm-lock.yaml, yarn.lock or bun lockfile triggers exit code 2 and a message naming the right tool and its runner. If a package-lock.json is present, or no lockfile exists, npm is allowed.

Example

you › Install zod and run the tests.

agent › In a folder with pnpm-lock.yaml the agent's npm install is refused with 'This project uses pnpm', and it reruns the step as pnpm add zod.

Questions

Does it catch npm inside a chained command?
Yes. A command such as 'cd app && npm test' is checked after the && and the semicolon and pipe separators too.
What if two lockfiles exist?
A package-lock.json next to another lockfile makes the hook allow npm, since the repo is ambiguous.
  • Inject Current Date

    HookWorkflow

    Free
  • Log Bash Commands

    HookWorkflow

    Free
  • Log Session End

    HookWorkflow

    Free
  • Notification Bell

    HookWorkflow

    Free