Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

vscode settings - Disable Prettier from formatting inline JS in HTML files in VS Code

I'm running Prettier through ESLint using the eslint-config-prettier and eslint-plugin-prettier packages. I also have Prettier as a dev dependency to use on non-JS files. I use these two extensions with VS Code to validate and format my code automatically on save: Prettier - Code formatter and ESLint.

I'm having a problem with inline JS in HTML files. It appears as though the Prettier run through ESLint is either not being run, or is being overruled by the regular Prettier extension, even though in my config file I've explicitly set the option html.format.contentUnformatted to "pre,code,textarea,script" to prevent formatting that content with the default formatter. I'd like it to ignore content within script tags since ESLint should be handling the formatting there.

The relevant settings in my settings.json:

{
  "javascript.validate.enable": false,  // turns off default VS Code validation, I'm using ESLint's
  "javascript.format.enable": false,    // ^ see above
  "editor.formatOnSave": true,          // Turn on formatting for all files except JS/JSX
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false
  },
  "eslint.alwaysShowStatus": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true // Let ESLint fix all fixable errors on save
  },
  "eslint.run": "onSave", // Run ESLint on save
  // Turn off Prettier for JS since we are doing it through Eslint already
  "prettier.disableLanguages": ["javascript", "javascriptreact"],
  "html.validate.scripts": false, // turn off default VSCode JS validation in HTML files
  "editor.defaultFormatter": "esbenp.prettier-vscode", // Use Prettier formatter
  "html.format.contentUnformatted": "pre,code,textarea,script" // Don't format content within these tags
}

Any idea what's wrong? I'm also open to suggestions of other ways to structure things. Thanks for any help!

question from:https://stackoverflow.com/questions/65895012/disable-prettier-from-formatting-inline-js-in-html-files-in-vs-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Prettier's embeddedLanguageFormatting option to achieve what you want. See https://prettier.io/docs/en/options.html#embedded-language-formatting

As for html.format.* VS Code settings, they're settings of the built-in formatter of VS Code and have nothing to do with Prettier.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...