核心提示:现在我们很多项目上都会使用eslint来规范一些写法,这样会使得我们的代码更加的一致,但是很多时候我们并不习惯使用eslint,而且一些eslint的写法虽然好,但是会多一些步骤,比如多写一个空格之类...
现在我们很多项目上都会使用eslint来规范一些写法,这样会使得我们的代码更加的一致,但是很多时候我们并不习惯使用eslint,而且一些eslint的写法虽然好,但是会多一些步骤,比如多写一个空格之类的,而我们平时在写代码的时候,也会借助编辑器的格式化来格式化代码,这样就省去了很多手工操作,但是有的时候编辑器的格式化方式跟eslint冲突,这个时候我们怎么解决呢?
下面介绍vscode下怎么解决这些问题,怎么让我们安心的写代码,不用管报错,只要我们格式化一些,保存一下就能解决大部分的eslint写法问题(不能解决的问题比如某个位置缺少一个逗号啊,变量创建但是没有使用啊,这些需要自己手动更改)
选择的编辑器是vscode,我们要使用eslint首先就要我们的项目是受eslint约束的,我们要npm安装eslint,并且安装一个叫做eslint的vscode的插件
随后我们打开用户设置进行配置,配置成每次保存的时候都使用eslint进行一次格式化,
{ "eslint.autoFixOnSave": true, "eslint.validate": [ "javascript", "javascriptreact", { "language": "html", "autoFix": true }, { "language": "vue", "autoFix": true } ] }
但是这个时候我们会遇到一些问题,如果我们使用的是默认的eslint设置,这时候是不允许后面有分号的,而我们格式化是会自动加上分号的,再比如分号的问题,原来的格式化是双引号而现在的是eslint要求是单引号,这是不行的
因此我们进行修改
"prettier.singleQuote": true, "prettier.semi": false,
我们还会遇到问题,那就是我们这个格式化,只能格式化js代码,而不能格式化template的html模板,这个是我们不希望的,因此我们需要安装vetur,默认属性是一行,我们设置属性分行
"vetur.format.defaultFormatter.html": "js-beautify-html", "vetur.format.defaultFormatterOptions": { "js-beautify-html": { // 属性强制折行对齐 "wrap_attributes": "force-aligned", } }, //空格 "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
如果我们使用了stylus,那么vscode安装stylus插件,进行设置,不适用冒号双引号大括号
"stylusSupremacy.insertColons": false, // 是否插入冒号 "stylusSupremacy.insertSemicolons": false, // 是否插入分好 "stylusSupremacy.insertBraces": false, // 是否插入大括号 "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否换行 "stylusSupremacy.insertNewLineAroundBlocks": false // 两个选择器中是否换行
下面贴上我自己的vscode配置
{ "vsicons.projectDetection.autoReload": true, "git.autofetch": true, "window.zoomLevel": 0, "emmet.syntaxProfiles": { "vue-html": "html", "vue": "html" }, "eslint.autoFixOnSave": true, "eslint.validate": [ "javascript", "javascriptreact", { "language": "html", "autoFix": true }, { "language": "vue", "autoFix": true } ], "fileheader.Author": "L", "fileheader.tpl": "/*\r\n * @Author: {author} \r\n * @Date: {createTime} \r\n * @Last Modified by: {lastModifiedBy} \r\n * @Last Modified time: {updateTime} \r\n */\r\n", "fileheader.LastModifiedBy": "L", "editor.tabSize": 2, "vetur.format.defaultFormatter.html": "js-beautify-html", "vetur.format.defaultFormatterOptions": { "js-beautify-html": { // 属性强制折行对齐 "wrap_attributes": "force-aligned", } }, "prettier.singleQuote": true, "prettier.semi": false, "vetur.format.defaultFormatter.js": "vscode-typescript", "beautify.tabSize": 2, "javascript.format.insertSpaceBeforeFunctionParenthesis": true, "[html]": {}, "files.associations": { "*.html": "html" }, "stylusSupremacy.insertColons": false, // 是否插入冒号 "stylusSupremacy.insertSemicolons": false, // 是否插入分好 "stylusSupremacy.insertBraces": false, // 是否插入大括号 "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否换行 "stylusSupremacy.insertNewLineAroundBlocks": false // 两个选择器中是否换行 }
"fileheader.Author": "L",
这个是fileheader插件的配置,可以在头部生成信息