VSCode中Prettier插件格式化异常:存文件时先错再恢或需二次保存
Hey there, let's sort out this annoying Prettier behavior you've been dealing with since last Monday—it sounds like it's throwing off your workflow big time! Based on your setup details, here are actionable steps to resolve the save-time formatting issues:
1. Fix VSCode Save Action Conflicts
Since you're using ESLint alongside Prettier (with plugin:prettier/recommended in your ESLint config), the most likely culprit is conflicting save-triggered actions. Let's align your VSCode settings to play nice:
Open your VSCode settings.json (press Cmd + Shift + P → "Preferences: Open Settings (JSON)") and add/update these lines:
"editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "prettier.eslintIntegration": true, "editor.defaultFormatter": "esbenp.prettier-vscode"
This ensures Prettier handles formatting, ESLint applies its fixes, and they don't step on each other's toes during saves.
2. Upgrade Your Outdated Prettier Version
You're running Prettier 1.19.1—that's a pretty old release, and it might not play well with your VSCode Prettier plugin v3.8.0. Let's get you on a stable, compatible version:
Run this in your project directory:
npm install prettier@latest --save-dev
After upgrading, double-check that your formatting preferences (like semi-colons or quotes) align with the latest Prettier defaults to avoid unexpected changes.
3. Disable Conflicting Formatting Plugins
If you have other formatting extensions (like Beautify, or any JS/TS formatters besides Prettier and ESLint) enabled in VSCode, they might be competing to format your files on save. Go to the Extensions panel, search for any non-essential formatters, and disable them temporarily to test if the glitch goes away.
4. Align ESLint and Prettier Rules
Your ESLint config has several rules that overlap with Prettier's functionality (like semi, quotes, comma-dangle). To prevent back-and-forth formatting, create a .prettierrc file in your project root to explicitly match your ESLint preferences:
{ "semi": false, "singleQuote": true, "trailingComma": "none", "printWidth": 100 }
This ensures both tools are on the same page for formatting rules, eliminating the "flash" of incorrect formatting.
5. Reset Prettier Plugin Settings
Sometimes VSCode plugin settings can get corrupted. Try resetting the Prettier extension:
- Open the Extensions panel
- Find "Prettier - Code formatter"
- Click the gear icon → Select "Reset Settings"
- Restart VSCode and test the save behavior again
If none of these steps work, try deleting your node_modules folder and package-lock.json, then run npm install to do a fresh dependency install. You could also create a minimal test project with your config to isolate if the issue is specific to your current codebase.
内容的提问来源于stack exchange,提问作者Nicolas Meienberger

