VSCode环境下配置ESLint 对Vue单文件的检测

本文介绍了在VSCode环境下如何配置eslint进行代码检查,并介绍了如何对.vue单文件进行支持。javascript

ESLint 安装

1.在工程根目录下,安装eslint及初始化css

$ npm install eslint --save-dev 
$ ./node_modules/.bin/eslint -- --init
//会输出几个问题,指引配置eslint,咱们选择通用方案便可
1.? How would you like to configure ESLint?  Use a popular style guide
2.? Which style guide do you want to follow? Standard
3.? What format do you want your config file to be in? JavaScript复制代码

2.经过以上步骤会在根目录下生成.eslintrc.js文件html

module.exports = {
    "extends": "standard"
};复制代码

3.输入如下命令尝试对.js文件进行eslint检测和修复vue

./node_modules/.bin/eslint -- --fix /path/to/file.js复制代码

4.安装vscode插件 ESLint java

该插件能够在编辑时自动进行eslint检测和保存修复等功能,免除频繁输入命令行,提升效率 node

安装完ESLint并重启vscode后,能够在VSCode中打开一个js文件,检查出错的地方就会有标红,且有eslint的提示。复制代码

5.设置保存时自动修复
打开vscode -> 首选项 ->设置 react

添加如下配置,便可实现保存时自动修复。es6

"eslint.autoFixOnSave": true,
 "eslint.validate":[
    {
       "language": "javascript",
     "autoFix": true
    }
    "javascriptreact",
 ]复制代码

须要注意的是,在ESLint的文档中有一段说明:
eslint.autoFixOnSave - enables auto fix on save. Please note auto fix on save is only available if VS Code's files.autoSave is either off, onFocusChange or onWindowChange. It will not work with afterDelay npm

即保存时自动修复的功能只有在vscode的files.autoSave 配置不为afterDelay时才能生效,此项配置默认为offbash

经过以上几步,咱们已经实现了在VSCode中对js文件编辑时检测,和保存自动修复的功能。

对Vue单文件检查

1.首先安装VSCode的插件 Vetur

该插件能够对Vue的三个代码块分别高亮,且提供脚手架命令快速生成一段Vue单文件模板,结合eslint可对三大部分进行代码检查复制代码

2.安装eslint-html插件,及修改配置文件,未安装时,没法正确识别vue文件中的 区域内的html代码

$ npm install eslint-plugin-html --save-dev

修改 eslintrc.js文件 
module.exports = {
    "extends": "standard",
    "plugins":[
        "html"
    ]
};复制代码

3.vscode -> 首选项 ->设置

"files.associations": {
     "*.vue": "vue"
},

"eslint.validate": [
    "javascript",
    "javascriptreact",
    {
        "language": "vue",
        "autoFix": true
    }
]复制代码

通过以上几步,不出意外就能够愉快地对.vue文件进行eslint检查,而且经过保存自动进行修复。能够提升之后的工做效率。

额外的配置项

  • 对es6的支持,如 import()函数

    //.eslintrc.js 文件
    module.exports = {
      "extends": "standard",
      "plugins":[
          "html"
      ],
      "parser": "babel-eslint",
      "env": { "es6": true },
      "rules": {
          //"off" or 0 - turn the rule off
          //"warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)
          //"error" or 2 - turn the rule on as an error (exit code is 1 when triggered)
    
          //require the use of === and !==
          "eqeqeq" : 0,
          "one-var": 0,
      }
    };复制代码
  • vue单文件style语法配置

若是在style中使用了scss,默认状况下, eslint会提示出错,此时须要设置style的lang属性,更改后便可正常提示

<style scoped lang='scss'>

</style>复制代码

以上

相关文章
相关标签/搜索