本文介绍了如何在VS Code编辑器中使用保存的自动修复功能,使用ESLint + Airbnb规则+ TypeScript + Stylelint for SCSS配置Vue CLI 4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是与我先前关于该主题的问题类似的问题,该问题未被部分解决,之后挑战的性质发生了很大变化:

在2019年,我非常着迷于获得一个``圣杯''工具设置,该工具配置为在TypeScript中使用 Vue 配置并使用 VS Code自动将代码保存在.vue,.ts中的文件中以及.scss文件.

In 2019 I was fairly obsessed by getting a 'holy grail' tooling setup configured with Vue in TypeScript and having VS Code to autofix your code on file save in .vue, .ts, and .scss files.

但要使更漂亮 ESLint Vetur 最终带来了太多挑战.由于与Prettier和ESLint具有部分相同的目标和相似的规则检查的内在冲突,并且由于Vetur为VS Code中的这种特定组合增加了更多的复杂性.

But getting Prettier to work optimally with ESLint and Vetur ended up being too much of a challenge. Because of an inherent clash with Prettier and ESLint having partly the same aim and similar rule checks, and with Vetur adding more complexity to this particular mix in VS Code.

此外,在大多数安装程序都可以正常工作的情况下,您需要连续多次保存文件,这很烦人.因为一旦ESLint找到并修复了一系列错误,就会出现新的错误,并且在清除所有错误之前,还没有足够的先进性来连续运行这些检查和修复...

Also when the setup was mostly working, it was rather irritating that you needed to save the file several times in a row. Because once ESLint found and fixed a set of errors, new errors appeared and it was not advanced enough to run those checks and fixes in a row until all was cleared...

2019年11月,我参加了Vue Conf多伦多会议,在Evan先生关于Vue 3.0的Deep Dive研讨会中,我不得不问他这个问题.他告诉我们,官方工具很快就会进行重大检修,并且新版本的ESLint将会引入新功能...

In November 2019 I was attending Vue Conf Toronto, and in Mr. Evan's workshop Deep Dive with Vue 3.0 I got to ask him about this problem. He told that the official tooling is going to see major overhauling pretty soon, and there will be new features coming in from newer versions of ESLint...

他还暗示,到目前为止,几乎所有Vue官方样式指南均已写入自动修复逻辑的规则检查,再加上即将推出的Vue 3.0完全模块化体系结构,甚至可能会看到正式的VS Code扩展.或者至少通过利用这些新功能,使Vetur和类似插件更易于运行代码检查和修复.

He also hinted that at this point there is autofix logic written to nearly all of Vue's official Style Guide's rule checks, which in combination with the upcoming Vue 3.0 fully modular architecture may even see an official VS Code extension coming. Or at least is making it easier for Vetur and similar plugins to run code checks and fixes by leveraging these new capabilities.

2019年12月, Vue CLI 4.1插件和预设升级带来了ESLint版本6功能.这意味着我们不仅可以开始使用 ESLint,还可以使用格式化程序,从而有效地减少设置中对Prettier的需求.

In December 2019, Vue CLI 4.1 plugins and presets upgrades brought ESLint version 6 features on the table. Which meant we could start using ESLint not just as a linter, but also a formatter, effectively dropping the need for Prettier in our setups.

与此同时,ESLint发布了官方VS Code扩展的第二版 dbaeumer .vscode-eslint ,支持VS Code的保存时运行代码操作-功能,由editor.codeActionsOnSave-设置控制.

During the same time ESLint released version 2 of it's official VS Code extension dbaeumer.vscode-eslint, bringing in support for VS Code's Run Code Actions on save -feature, controlled by editor.codeActionsOnSave -setting.

因此,最终清除了运行此安装程序的路径! 接下来,我将回答有关如何配置此混音的我自己的问题.

So finally the path was cleared for getting this setup running! Next up, I'll answer my own question on how to configure this mix.

PS.尽管Vetur仍可以用作此设置的一部分,但在这里我已更改为使用Stylelint. Stylelint的自动修复功能仍然存在一些问题,但可能会在以后的更新中解决. 不过,我仍然很想知道Vetur在有或没有Stylelint的情况下是否有用!

PS. While it's possible Vetur could still be used as a part of this setup, here I've changed to using Stylelint. There has still been some problems with Stylelint's autofix feature, but is likely to be solved by future updates. Yet I'm still interested in hearing if Vetur would prove useful with or without Stylelint!

推荐答案

正式的脚手架Vue CLI项目的配置

在2020年2月升级Vue CLI 4.2的创建项目支架之后,您可以通过全局vue create myproject命令创建一个新项目并至少进行以下选择来完成配置的一半(包括配置)如下):

Official scaffolded Vue CLI project's configurations

After Vue CLI 4.2 upgrades in create project scaffolding in February 2020, you are half way through the configurations by creating a new project with global vue create myproject command and making at least these selections (configurations included below):

Vue CLI v4.2.2
? Please pick a preset: Manually select features
? Check the features needed for your project:
 (*) Babel
 (*) TypeScript
 ( ) Progressive Web App (PWA) Support
 ( ) Router
 ( ) Vuex
 (*) CSS Pre-processors
>(*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n) Y

? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
  Sass/SCSS (with dart-sass)
> Sass/SCSS (with node-sass)
  Less
  Stylus

? Pick a linter / formatter config:
  ESLint with error prevention only
> ESLint + Airbnb config
  ESLint + Standard config
  ESLint + Prettier
  TSLint (deprecated)

? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Lint on save
 ( ) Lint and fix on commit

? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files
  In package.json

现在您可能想知道为什么我在第一个建议的选项dart-sass上选择了node-sass-这就是为什么:

Now you may be wondering why I chose node-sass over the first suggested option dart-sass − here's why: Vue CLI CSS pre-processor option: dart-sass VS node-sass?

package.json中,至少为您提供了这些依赖项:

In package.json you are given at least these dependencies:

  "dependencies": {
    "core-js": "^3.6.4",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.18.0",
    "@typescript-eslint/parser": "^2.18.0",
    "@vue/cli-plugin-babel": "~4.2.0",
    "@vue/cli-plugin-eslint": "~4.2.0",
    "@vue/cli-plugin-typescript": "~4.2.0",
    "@vue/cli-service": "~4.2.0",
    "@vue/eslint-config-airbnb": "^5.0.2",
    "@vue/eslint-config-typescript": "^5.0.1",
    "eslint": "^6.7.2",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-vue": "^6.1.2",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2",
    "typescript": "~3.7.5",
    "vue-template-compiler": "^2.6.11"
  }

使用.eslintrc.js:

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/essential',
    '@vue/airbnb',
    '@vue/typescript/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
  },
};

使用.editorconfig:

[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100

对配置和格式进行了偏见的配置更改

所以,根据我对.eslintrc.js的偏见修改:

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/recommended',
    '@vue/airbnb',
    '@vue/typescript/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  rules: {
    'class-methods-use-this': 0,
    // Changing max row length from 80 to 150.
    // Remember to change in .editorconfig also, although am not sure if that file is even needed?
    // Especially as scaffolding gave 100 as max len while ESLint default is 80...
    'max-len': [
      'error',
      {
        code: 150,
        ignoreComments: true,
        ignoreUrls: true,
      },
    ],
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    '@typescript-eslint/ban-ts-ignore': 0,
  },
  // These are added if you chose also to install Jest plugin for Vue CLI
  // With my own modifications here as an example
  overrides: [
    {
      files: [
        './src/**/__tests__/*.spec.{j,t}s',
        './src/**/__mock__/*.{j,t}s',
      ],
      env: {
        jest: true,
      },
      rules: {
        'no-unused-expressions': 0,
      },
    },
  ],
};

然后我添加了.eslintignore文件:

# Lint config files in the root ending .js
!/*.js

然后,我在.editorconfig顶部添加了此部分(虽然不确定是否需要此文件):

Then I've added this section in top of .editorconfig (while not sure if this file is needed):

# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

安装和配置Stylelint

Stylelint 与CSS/SCSS/SASS/LESS/Stylus有点类似,而ESLint用于JavaScript/TypeScript ,同样可以通过插件和预设进行扩展.它具有官方的VS Code扩展,也可以在您的Webpack构建过程中运行.

Installing and configuring Stylelint

Stylelint is a somewhat similar project to CSS/SCSS/SASS/LESS/Stylus than ESLint is for JavaScript/TypeScript, being likewise extendable with plugins and presets. It has an official VS Code extension, and it can also be run during your Webpack build process.

我选择使用 stylelint-scss包扩展Stylelint.每周半百万的下载量,以及 stylelint-config-recommended-scss包来自同一维护者.另外,我已经将 stylelint-webpack-plugin 配置为Webpack的构建过程.

I've chosen to extend Stylelint with stylelint-scss package, which currently has half a million of weekly downloads, and stylelint-config-recommended-scss package from the same maintainer. In addition, I've configured stylelint-webpack-plugin as a part of the Webpack build process.

通过以下命令从命令行安装这些dev依赖项:npm i -D stylelint stylelint-config-recommended-scss stylelint-scss stylelint-webpack-plugin

Install these dev dependencies from the command line by: npm i -D stylelint stylelint-config-recommended-scss stylelint-scss stylelint-webpack-plugin

添加带有一些偏向规则修改的文件.stylelintrc.json作为示​​例(可能需要Vue的::v-deep自定义选择器处理):

Add a file .stylelintrc.json with a few biased rule modifications as an example (Vue's ::v-deep custom selector handling may come needed):

{
  "extends": "stylelint-config-recommended-scss",
  "rules": {
    "max-nesting-depth": 4,
    "no-descending-specificity": null,
    "property-no-unknown": [
      true,
      {
        "ignoreProperties": ["user-drag", "font-smooth"]
      }
    ],
    "selector-pseudo-element-no-unknown": [
      true,
      {
        "ignorePseudoElements": ["v-deep"]
      }
    ]
  }
}

创建文件或添加到vue.config.js,这是一些有偏见的配置示例:

Create file or add to vue.config.js, this some biased config examples:

// Add in the top of the file
const StyleLintPlugin = require('stylelint-webpack-plugin');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        // Here as example if needed:
        // Import Sass vars and mixins for SFC's style blocks
        prependData: '@import "@/assets/styles/abstracts/_variables.scss"; @import "@/assets/styles/abstracts/_mixins.scss";',
      },
    },
  },
  lintOnSave: process.env.NODE_ENV !== 'production',
  productionSourceMap: false,
  devServer: {
    overlay: {
      warnings: true,
      errors: true,
    },
  },
  configureWebpack: {
    // Fast source maps in dev
    devtool: process.env.NODE_ENV === 'production' ? false : 'cheap-eval-source-map',
    plugins: [
      new StyleLintPlugin({
        files: 'src/**/*.{vue,scss}',
      }),
    ],
    resolve: {
      alias: {
        // Alias @ to /src folder for ES/TS imports
        '@': path.join(__dirname, '/src'),
      },
    },
  },
};

VS Code编辑器,扩展和设置

在项目根目录中创建.vscode命名文件夹,以放置项目特定的设置和扩展建议.请注意,如果您在工作空间模式(一次包含多个项目根目录)下打开VS Code,则某些设置在该模式下不起作用,因此我总是不使用工作空间模式而直接打开项目根目录.

VS Code editor, extensions and settings

Create .vscode named folder in your project root for placing project specific settings and extension recommendations. Note that if you open VS Code in workspace mode (having multiple project roots included at once), some of the settings do not work in this mode, so I'm always opening the project root directly without using workspace mode.

在该文件夹中添加文件extensions.json,至少建议使用此内容,然后安装扩展名.

In this folder add a file extensions.json, with at least this content recommended, and install the extensions.

{
  "recommendations": [
    // ESLint - Integrates ESLint JavaScript into VS Code.
    "dbaeumer.vscode-eslint",
    // Disable eslint rule - Disable eslint rule with one click.
    "wooodhead.disable-eslint-rule",
    // eslint-disable-snippets - Simple snippets for disable eslint rules
    "drknoxy.eslint-disable-snippets",
    // Vue - Syntax highlight for Vue.js
    "jcbuisson.vue",
    // stylelint - Modern CSS/SCSS/Less linter
    "stylelint.vscode-stylelint",
    // EditorConfig for VS Code - EditorConfig Support for Visual Studio Code
    // Not sure if this is needed or recommended,
    // but .editorconfig file is still included in the scaffolded project...
    "editorconfig.editorconfig",
    // DotENV - Support for dotenv file syntax.
    "mikestead.dotenv",
  ]
}

添加具有以下或类似设置的另一个文件settings.json:

Add another file settings.json with these or similar settings:

{
  // EDITOR
  // ----------------------------------------
  "editor.defaultFormatter": "dbaeumer.vscode-eslint",
  "[javascript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" },
  "[typescript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" },
  "[vue]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" },
  "[scss]": { "editor.defaultFormatter": "stylelint.vscode-stylelint" },
  "[css]": { "editor.defaultFormatter": "stylelint.vscode-stylelint" },
  "editor.codeActionsOnSave": {
    // https://github.com/microsoft/vscode-eslint/blob/master/README.md#release-notes
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },

  // ESLINT
  // ----------------------------------------
  "eslint.enable": true,
  "eslint.alwaysShowStatus": true,
  "eslint.options": {
    "extensions": [".html", ".js", ".ts", ".vue"]
  },

  // VETUR
  // Disable rules if user has extension installed and enabled.
  // ----------------------------------------
  "vetur.validation.template": false,
  "vetur.validation.style": false,
  "vetur.format.defaultFormatter.html": "none",
  "vetur.format.defaultFormatter.css": "none",
  "vetur.format.defaultFormatter.scss": "none",
  "vetur.format.defaultFormatter.js": "none",
  "vetur.format.defaultFormatter.ts": "none",

  // STYLELINT
  // ----------------------------------------
  "stylelint.enable": true,
  "css.validate": true,
  "scss.validate": true,

  // HTML
  // ----------------------------------------
  "html.format.enable": false,
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "vue-html": "html"
  },

  // FILES
  // ----------------------------------------
  "files.exclude": {
    "**/*.log": true,
    "**/*.log*": true,
    "**/dist": true,
  },
  "files.associations": {
    ".babelrc": "jsonc",
    ".eslintrc": "jsonc",
    ".markdownlintrc": "jsonc",
    "*.config.js": "javascript",
    "*.spec.js": "javascript",
    "*.vue": "vue"
  },
  // The default end of line character. Use \n for LF and \r\n for CRLF.
  "files.eol": "\n",
  "files.insertFinalNewline": true,
  "files.trimFinalNewlines": true,
  "files.trimTrailingWhitespace": true,
}

这些是我偏颇的项目设置,我有兴趣听取改进建议!

So these were my biased project settings, and I'm interested in hearing improvement suggestions!

这篇关于如何在VS Code编辑器中使用保存的自动修复功能,使用ESLint + Airbnb规则+ TypeScript + Stylelint for SCSS配置Vue CLI 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 04:17