vscode保存按照eslint规则自动格式化

4,231 阅读1分钟

最近写vue用了vue-admin-template,npm run dev跑起来总是有eslint报错,每次检查耗时耗力,记录解决方法。

1.安装插件

vscode安装以下插件:

  • eslint
  • Vetur
  • Prettier - Code formatter

2.vue文件保存时格式化

按住·commond+shift+p·,搜索 perferences open setting(json)。

image.png

在配置文件中添加以下内容,注意不要直接所有拷贝进去,可能会覆盖到你自己的配置。建议拷贝进去然后去除重复的key即可。

{

"editor.suggestSelection": "first",

"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",

"explorer.confirmDelete": false,

"editor.tabSize": 2,

"files.autoSave": "onFocusChange",

"editor.fontSize": 14, // 设置字体

"editor.tabCompletion": "on", // 用来在出现推荐值时,按下Tab键是否自动填入最佳推荐值

"editor.codeActionsOnSave": {

"source.fixAll.eslint": true,

"source.organizeImports": true // 这个属性能够在保存时,自动调整 import 语句相关顺序,能够让你的 import 语句按照字母顺序进行排列

},

"editor.formatOnSave": true,

// #让vue中的js按"prettier"格式进行格式化

"vetur.format.defaultFormatter.html": "js-beautify-html",

"vetur.format.defaultFormatter.js":"prettier-eslint",

"vetur.format.defaultFormatterOptions": {

"js-beautify-html": {

// #vue组件中html代码格式化样式

"wrap_attributes": "auto", //也可以设置为“auto”,效果会不一样

"wrap_line_length": 200,

"end_with_newline": false,

"semi": false,

"singleQuote": true

},

"prettier": {

"semi": false,

"singleQuote": true,

"editor.tabSize": 2

},

"prettyhtml": {

"printWidth": 160,

"singleQuote": false,

"wrapAttributes": false,

"sortAttributes": false

}

},

"[vue]": {

"editor.defaultFormatter": "octref.vetur"

},

"bracketPairColorizer.depreciation-notice": false,

"editor.mouseWheelZoom": true

}

问题记录

格式化目录下所有文件

下载插件Start Format Files,然后右键目录选择 开始格式化文件即可。

image.png

忽略文件配置见marketplace.visualstudio.com/items?itemN…