Skip to content

vscode 配置 vue 开发环境

vscode + vue 让开发效率提升一个档次。


自动生成 vue 代码片段

需要安装的插件有ESLint、Prettier、Vetur、Vue 3 Snippets

通过设置vscode生成vue代码片段可快速生成vue模版文件。

文件 -> 首选项 -> 用户片段选择 vue.json,添加如下内容:

json
{
  "vue output to vue-template": {
    "prefix": "vue",
    "body": [
      "<template>",
      "\t<div class=\"\">\n\t$2</div>",
      "</template>",
      "",
      "<script>",
      "export default {",
      "\tcomponents: {},",
      "\tprops: {},",
      "\tdata () {",
      "\t\treturn {}",
      "\t},",
      "\tcomputed: {},",
      "\tcreated: function () {},",
      "\tmounted: function () {},",
      "\tmethods: {}",
      "}",
      "</script>",
      "",
      "<style scoped lang=\"less\">",
      "",
      "</style>\n"
    ],
    "description": "vue output to vue-template"
  }
}

vue代码格式化

目的:为了统一代码风格,通过eslint代码审查。

插件:eslint + vetur + prettier

三个插件的作用是什么?这三个插件必须都安装吗?

先来说说这三个插件的作用

  • eslint:

    检查代码质量,比如是否有已定义但未使用的变量或者使用函数式编程的函数是否产生副作用等。

    查代码风格 (只是少部分),比如每行的最大长度,或者是否使用拖尾逗号等。

    修复space-before-function-parent等问题。

  • pretter:

    没有对代码的质量进行检查的能力,其只会对代码风格按照指定的规范进行统一,避免一个项目中出现多种不同的代码风格。

  • vetur:

    代码高亮、支持特定类型的代码片段、emmet语法、代码语法检查、样式美化、代码提示、主流框架支持,但是vetur只能作用于 _.vue 文件,其他的文件像 _.js *.html 等还需要使用 Prettier 来配合格式化,但是其内置了js-beautify-html工具可用来格式化html等代码。

再来说说这三个插件都要安装的问题:

个人推荐:

必须安装的有:ESLint、Vetur

可选安装的插件:prettier,因为vue中的js代码我选择的是使用vscode自带的格式化工具vscode-typescript来格式化代码再搭配eslint修复,而vue中的html和css使用的是vetur自带的工具js-beautify-html来格式化,另外vetur中内置了prettier,prettier-eslint等工具,所以我没有安装prettier。

下面提供了两种方法对vue代码格式化,这两种方法区别就是是否使用prettier。

使用ESLint + Vetur格式化代码

原理:利用vetur内置的工具对vue代码中的html、js、css三个类型的代码进行分块格式化,只需按下ctrl+S就可一键格式化vue代码。

当按下 ctrl + S 时会触发的动作:

  • 使用 vetur 中js-beautify-html的配置对html进行格式化;

  • 调用 vscode-typescript 来处理vue文件中js代码的格式化。

  • 让 eslint 修复已经存在的字符串的双引号及尾部跟;符号的问题。

  • “javascript.format.insertSpaceBeforeFunctionParenthesis": true, 解决函数名前面不加空格的问题

  • ”javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false, 让函数{}中不添加空格

使用此方法需把 vetur 中的 eslint-plugin-vue 检查去掉,如下图:

wwwechoxu

使用此方法不用配置项目的根目录中的.eslintrc.js及项目根目录中的.prettierc.js,也不要在vetur中配置prettier选项更不用安装prettier。

文件 -> 首选项 -> 设置 -> settings.json,添加如下内容:

json
{
  
  // 默认全局配置
  "workbench.colorTheme": "Community Material Theme Palenight",
  "workbench.iconTheme": "vscode-great-icons",
  "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
  "liveServer.settings.donotVerifyTags": true,
  "liveServer.settings.donotShowInfoMsg": true,
  "editor.tabSize": 2, //设置vscode默认的缩进格式,两个空格
  
  
  // 保存时自动检测代码并格式化
  // 在新版的 ESLint 2.0.4以上中已经支持了对 *.vue 文件的校验,所以无需再进行这项配置了是通过eslint.probe 配置的而eslint.validate已经废弃了,只需要添加一个保存时自动修复 ESLint 错误的功能就行了。详细请查看:https://github.com/Microsoft/vscode-eslint
  
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },

  // js函数相关配置
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true, // 让函数(名)和后面的括号之间加个空格
  "javascript.format.semicolons": "remove", // 移除js语句的分号
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false, // 函数{}中不添加空格,详细的请参考https://code.visualstudio.com/docs/getstarted/settings
  
  
  // vetur配置
  "vetur.format.defaultFormatter.js": "vscode-typescript",  // 使用vscode自带的代码工具对js代码格式化
  
  "vetur.format.defaultFormatter.html": "js-beautify-html",  // vue中的html代码通过js-beautify-html格式化

  "vetur.grammar.customBlocks": {
    "docs": "md",
    "i18n": "json"
  },
    
  "vetur.format.options.tabSize": 2,  // 设置vetur格式化时缩进为2个空格
  "vetur.format.options.useTabs": false,

  "vetur.format.defaultFormatterOptions": {
  
    // vue中的html格式化时用到的选项
    "js-beautify-html": {
      // Wrap attributes to new lines [auto|force|force-aligned|force-expand-multiline] ["auto"]
      // - auto: 仅在超出行长度时才对属性进行换行。
      // - force: 对除第一个属性外的其他每个属性进行换行。
      // - force-aligned: 对除第一个属性外的其他每个属性进行换行,并保持对齐。
      // - force-expand-multiline: 对每个属性进行换行。
      // - aligned-multiple: 当超出折行长度时,将属性进行垂直对齐。

      "wrap_attributes": "auto",
      "wrap_line_length": 100,
      "semi": false,
      "singleQuote": true,
      "sortAttributes": true
    }
  },

  "[vue]": {
    "editor.defaultFormatter": "octref.vetur" // 设置默认的vue格式化工具
  }
  
 
  // 指定 *.js 文件的格式化工具为vscode自带
  // "[javascript]": {
  //   "editor.defaultFormatter": "vscode.typescript-language-features"
  // },
  // // 默认使用prettier格式化支持的文件需指定prettier选项,当值为”none”时禁止prettier
  // "editor.defaultFormatter": "esbenp.prettier-vscode"

  //   "vetur.format.defaultFormatter.html": "prettier",
  //   "vetur.format.defaultFormatter.pug": "prettier",
  //   "vetur.format.defaultFormatter.css": "prettier",
  //   "vetur.format.defaultFormatter.postcss": "prettier",
  //   "vetur.format.defaultFormatter.scss": "prettier",
  //   "vetur.format.defaultFormatter.less": "prettier",
  //   "vetur.format.defaultFormatter.stylus": "stylus-supremacy",
  //   "vetur.format.defaultFormatter.js": "prettier",
  //   "vetur.format.defaultFormatter.ts": "prettier",
  

  // 让vetur支持sass 需先安装 yarn install sass-indented
  // enables debug mode.
  // "sass.format.debug": false,
  // // removes empty rows.
  // "sass.format.deleteEmptyRows": true,
  // // removes trailing whitespace.
  // "sass.format.deleteWhitespace": true,
  // // Convert scss/css to sass.
  // "sass.format.convert": true,
  // // If true space between the property: value, is always set to 1.
  // "sass.format.setPropertySpace": true
  // "vetur.format.defaultFormatter.sass": "sass-formatter"
}

还需创建jsconfig.json,防止 vetur 启动时报 warning 信息

json
{
  "include": ["./src/*"]
}

使用vuter + eslint + prettier格式化vue代码

与上一种方法相比,此方法用到了prettier而不是上面的vscode的格式化工具,同时增加了vetur中配置prettier的选项。

原理:vetur调用内置的工具让vue 文件中不同的块使用不同的格式化方案。vue中的<script> 用vetur内置的prettier进行格式化,而<template><style>等用js-beautify-html格式化,最后用eslint对代码进行审查修复。

详细配置:

json
{
  // 默认全局配置
  "workbench.colorTheme": "Community Material Theme Palenight",
  "workbench.iconTheme": "vscode-great-icons",
  "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
  "liveServer.settings.donotVerifyTags": true,
  "liveServer.settings.donotShowInfoMsg": true,
  "editor.tabSize": 2,
 

  // 保存时自动检测代码并格式化
  
  // 在新版的 ESLint 2.0.4以上中已经支持了对 *.vue 文件的校验,所以无需再进行这项配置了是通过eslint.probe 配置的而eslint.validate已经废弃了,只需要添加一个保存时自动修复 ESLint 错误的功能就行了。详细请查看:https://github.com/Microsoft/vscode-eslint
  
  "editor.formatOnSave": true,
  
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },

  
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true, // 函数名前面加空格
  "javascript.format.semicolons": "remove", // 移除js语句的分号
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false, // 函数{}中不添加空格,详细的请参考https://code.visualstudio.com/docs/getstarted/settings

  // vetur配置
  "vetur.format.defaultFormatter.js": "prettier",  // 还可尝试prettier-eslint
  // "vetur.format.defaultFormatter.js": "none",   // 禁用vetur的JS格式化,交给eslint处理
  "vetur.format.defaultFormatter.html": "js-beautify-html",
  "vetur.grammar.customBlocks": {
    "docs": "md",
    "i18n": "json"
  },
  "vetur.format.options.tabSize": 2,
  "vetur.format.options.useTabs": false,
  "vetur.format.defaultFormatterOptions": {
  // 使用vetur内置的prettier对vue中的js代码格式化。
    "prettier": {
            "tabWidth": 2,
            "useTabs": false,
            "semi": false,
            "singleQuote": true, // 使用单引号
            "trailingComma": "none", // 是否使用尾逗号,可选值"<none|es5|all>",默认none
            "printWidth": 100,
            "bracketSpacing": false, // 大括号内的首尾需要空格
            "arrowParens": "avoid", // allow paren-less arrow functions 箭头函数的参数使用圆括号
            "endOfLine": "auto", // 行尾换行方式,可选值"<auto|lf|crlf|cr>",默认auto
            "jsxBracketSameLine": false  // jsx 标签的反尖括号需要换行
          },
          
    "js-beautify-html": {
      // Wrap attributes to new lines [auto|force|force-aligned|force-expand-multiline] ["auto"]
      "wrap_attributes": "auto",
      "wrap_line_length": 100,
      "semi": false,
      "singleQuote": true,
      "sortAttributes": true
    }
  },
  "[vue]": {
    "editor.defaultFormatter": "octref.vetur"  // 设置默认vue格式化工具vetur,当你还安装了prettier插件(非vetur内置的prettier)时且需要用prettier格式化代码时需在项目根目录中添加.prettierc.js文件从而对prettier配置,在setting.json中对prettier相关的配置不生效必须写在.prettier.js文件中。
  },

}

其他配置文件

prettier-eslint 功能是先使用 prettier 格式化代码风格再用 eslint 验证语法然后再进一步根据 eslint 格式化代码

.editorconfig 文件

主要用于配置 IDE

规范缩进风格,缩进大小,tab 长度以及字符集等,解决不同 IDE 的编码范设置。EditorConfig 插件会去查找当前编辑文件的所在文件夹或其上级文件夹中是否有 .editorconfig 文件。如果有,则编辑器的行为会与 .editorconfig 文件中定义的一致,并且其优先级高于编辑器自身的设置。

json
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
charset = utf-8
insert_final_newline = true  // 是否在文件的最后插入一个空行  可选true和false
trim_trailing_whitespace = true  // 是否删除行尾的空格  可选择true和false

.eslintignore 文件

放置需要 ESLint 忽略的文件,只对.js 文件有效

shell
/build/
/config/
/dist/
/src/utils/
/src/router/*.js

.eslintrc.js 文件

用来配置 ESLint 的检查规则

注意: 此项一般在 settings.json 中没有配置"vetur.format.defaultFormatter.js": "none",时才需要添加

js
module.exports = {
  //此项是用来告诉eslint找当前配置文件不能往父级查找
  root: true,
  //此项是用来指定eslint解析器的,解析器必须符合规则,babel-eslint解析器是对babel解析器的包装使其与ESLint解析
  parser: "babel-eslint",
  //此项是用来指定javaScript语言类型和风格,sourceType用来指定js导入的方式,默认是script,此处设置为module,指某块导入方式
  parserOptions: {
    sourceType: "module",
  },
  //此项指定环境的全局变量,下面的配置指定为浏览器环境
  env: {
    browser: true,
  },
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  // 此项是用来配置标准的js风格,就是说写代码的时候要规范的写,如果你使用vs-code我觉得应该可以避免出错
  extends: "standard",
  // required to lint *.vue files
  // 此项是用来提供插件的,插件名称省略了eslint-plugin-,下面这个配置是用来规范html的
  plugins: ["html"],
  // add your custom rules here
  // 下面这些rules是用来设置从插件来的规范代码的规则,使用必须去掉前缀eslint-plugin-
  // 主要有如下的设置规则,可以设置字符串也可以设置数字,两者效果一致
  // "off" -> 0 关闭规则
  // "warn" -> 1 开启警告规则
  //"error" -> 2 开启错误规则
  // 了解了上面这些,下面这些代码相信也看的明白了
  rules: {
    // allow async-await
    "generator-star-spacing": "off",
    // allow debugger during development
    "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",
    // js语句结尾必须使用分号
    'semi': ["off", "always"],
    // 三等号
    'eqeqeq': 0,
    // 强制在注释中 // 或 /* 使用一致的空格
    "spaced-comment": 0,
    // 关键字后面使用一致的空格
    "keyword-spacing": 0,
    // 强制在 function的左括号之前使用一致的空格
    "space-before-function-paren": 0,
    // 引号类型
    'quotes': [0, "single"],
    // 禁止出现未使用过的变量
    // 'no-unused-vars': 0,
    // 要求或禁止末尾逗号
    "comma-dangle": 0,
    'func-call-spacing': ["error", "always"]
  },
}

.prettier.js或.prettierrc文件

当vscode安装了prettier插件时需要在项目的根目录下创建此文件:

注意: 当使用vetur内置的prettier时不用配置此项

json
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": false,
  "singleQuote": true,
  "eslintIntegration": true,
  "trailingComma": "none",
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "jsxBracketSameLine": false
}

最后附上我的settings.json:

json
{
  // 默认全局配置
  "workbench.colorTheme": "Community Material Theme Palenight",
  "workbench.iconTheme": "vscode-great-icons",
  "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
  "liveServer.settings.donotVerifyTags": true,
  "liveServer.settings.donotShowInfoMsg": true,
  "editor.tabSize": 2,
  // 保存时使用eslint检测代码并自动格式化
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  // 详细的vscode请参考https://code.visualstudio.com/docs/getstarted/settings
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true, // 函数名前面加空格
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false, // 函数{}中不添加空格
  "javascript.format.semicolons": "remove", // 移除js语句的分号
  // vetur配置
  "vetur.format.defaultFormatter.js": "vscode-typescript",
  "vetur.format.defaultFormatter.html": "js-beautify-html",
  "vetur.grammar.customBlocks": {
    "docs": "md",
    "i18n": "json"
  },
  "vetur.format.options.tabSize": 2,
  "vetur.format.options.useTabs": false,
  "vetur.format.defaultFormatterOptions": {
    "js-beautify-html": {
      // Wrap attributes to new lines [auto|force|force-aligned|force-expand-multiline] ["auto"]
      "wrap_attributes": "auto",
      "wrap_line_length": 100,
      "semi": false,
      "singleQuote": true,
      "sortAttributes": true
    }
  },
  "[vue]": {
    "editor.defaultFormatter": "octref.vetur"
  },
}

常用插件

json
Auto Close Tag
Auto Rename Tag
Bracket Pair Colorizer
Chinese (Simplified) Language Pack for Visual Studio Code
Community Material Theme
ESLint
HTML Snippets
Live Server
Vetur
VSCode Great Icons
Vue 3 Snippets