VS Code中保存文件后HTML与EJS标签格式错乱问题求助
Hey there! I totally get how frustrating it is when your clean EJS code gets mangled on save—let's sort this out while keeping the "format on save" feature working for you. Here are targeted solutions based on your current setup:
1. Adjust VS Code's Built-in HTML Formatter Settings
Since you've associated .ejs files with HTML, we can tweak the built-in HTML formatter to play nice with EJS tags. Open your settings.json (press Ctrl/Cmd + Shift + P, type "Open Settings (JSON)") and add these rules:
{ // Keep your existing EJS associations if needed "files.associations": { "*.ejs": "html" }, "[html]": { "editor.defaultFormatter": "vscode.html-language-features", "editor.formatOnSave": true, // Disable automatic line wrapping for tags containing EJS "html.format.wrapLineLength": 0, // Prevent unnecessary newlines inside tags "html.format.preserveNewLines": false, "html.format.maxPreserveNewLines": 1, // Stop indenting content inside HTML tags (fixes EJS tag indentation chaos) "html.format.indentInnerHtml": false, // Don't add extra newlines around specific tags "html.format.extraLiners": "" } }
These settings will:
- Keep EJS tags and surrounding HTML elements on the same line
- Eliminate unwanted indentation after EJS blocks
- Preserve your original line structure while still applying basic formatting
2. Use a Dedicated EJS Formatter Extension
If the built-in HTML formatter still doesn't cut it, try a formatter designed specifically for EJS:
- Install the EJS Formatter extension (ID:
koichik.vscode-ejs-formatter) from the VS Code Marketplace - Update your settings.json to use this formatter for EJS files:
{ "files.associations": { "*.ejs": "ejs" // Switch from html to ejs to use the dedicated formatter }, "[ejs]": { "editor.defaultFormatter": "koichik.vscode-ejs-formatter", "editor.formatOnSave": true } }
This extension understands EJS syntax natively, so it won't split your tags or add random indentation around <%= %> blocks.
3. Tweak EditorConfig Rules (If You're Using It)
If you have an .editorconfig file in your project, add these lines to ensure consistency for EJS files:
[*.ejs] indent_style = space indent_size = 2 max_line_length = 0 // Disable line wrapping trim_trailing_whitespace = true insert_final_newline = true
This will override any conflicting formatting rules from EditorConfig that might be causing issues.
Quick Check Before Testing
- Make sure you've removed the
editor.defaultFormatter: Nonesetting (replace it with the formatter you choose above) - Restart VS Code after updating settings to apply changes
Test saving your EJS files now—your tags should stay on the same line, and indentation should behave as expected!
内容的提问来源于stack exchange,提问作者Jeffery Park

