lint-staged自动追加文件路径至命令末尾的原因咨询
Great question! The behavior you're seeing is actually lint-staged's core functionality—it’s designed to pass the paths of staged files directly to the commands you configure. Let me break down what’s happening and how to fix it:
What’s causing the issue?
When you set up lint-staged like this:
"lint-staged": { "*.{js, json}": "npm run lint" }
Lint-staged scans for all staged .js and .json files, then appends their full paths to the end of your npm run lint command. That’s why you end up with a malformed command like:
npm ERR! app@1.0.0 lint: 'npm run v2:lint "C:/dev/codes/my-app/v2/app/index.js"'
The problem is your v2:lint script (cd ./v2 && npm run lint && cd ..) doesn’t expect or handle these extra file path arguments. When npm passes those paths along, it breaks the command structure your v2 project’s lint tool is expecting.
How to fix it
You have a couple of solid options depending on your goal:
Option 1: Keep linting the entire v2 directory (ignore staged files)
If you don’t need to target only staged files and just want to run a full v2 lint check on every commit, modify your lint-staged config to wrap the command in a shell that ignores extra arguments:
"lint-staged": { "*.{js, json}": ["bash -c 'npm run lint'"] }
For Windows compatibility, use cmd /c "npm run lint" instead, or install cross-env-shell for cross-platform support:
"lint-staged": { "*.{js, json}": ["npx cross-env-shell 'npm run lint'"] }
Option 2: Lint only staged files (better practice)
If you want to leverage lint-staged’s strength and only lint the specific files you’re committing, adjust your scripts and config to pass file paths correctly:
- Update your
v2:lintscript to capture and forward the file path arguments:
"scripts": { "lint": "npm run v2:lint", "v2:lint": "cd ./v2 && npm run lint -- $@ && cd .." }
The $@ here grabs all arguments passed to the script and passes them directly to the v2 project’s lint command.
- Tweak lint-staged to target only files in the v2 directory (so you don’t accidentally run lint on root-level files):
"lint-staged": { "v2/**/*.{js, json}": ["npm run v2:lint --"] }
The -- ensures npm passes the file paths through to the v2:lint script instead of interpreting them as npm flags.
This setup will make lint-staged pass only the staged v2 files to your lint command, and your script will correctly forward those paths to the v2 project’s lint tool (like ESLint)—exactly the targeted workflow lint-staged is built for!
内容的提问来源于stack exchange,提问作者jamesdeath123

