vscode + vite + vue3 + ts + eslint + stylelint 代码自动格式化

17,142 阅读2分钟

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

使用 vite 创建的 vue3 项目有点简陋,很多功能都没有。所以本文将讲解一下如何对 vite + vue3 项目配置代码自动格式化。配置完成后的效果如下图所示:

10月-24-2021 22-06-50.gif

安装 VSCode 插件

打开 VSCode,安装以下插件:

eslint
stylelint
volar

image.png

打开 VSCode 配置文件(Mac command + shift + p,windows ctrl + shift + p,输入 settings)。

image.png

在配置文件中加入以下代码:

"editor.codeActionsOnSave": {
    "source.fixAll": true,
},
"eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
],
"eslint.alwaysShowStatus": true,
"stylelint.validate": [
    "css",
    "less",
    "postcss",
    "scss",
    "sass"
],

安装项目依赖

安装以下依赖:

npm i -D eslint eslint-config-airbnb-vue3-ts sass stylelint stylelint-config-standard-scss stylelint-scss

配置 .eslintrc.js .stylelintrc.js 文件

我的 eslint 配置是基于 airbnb 规范的, css 规范用的是官方插件。

.eslintrc.js 文件

module.exports = {
    root: true,
    env: {
        browser: true,
        node: true,
        es6: true,
        jest: true,
    },
    extends: ['eslint-config-airbnb-vue3-ts'],
    ignorePatterns: ['iconfont.js'],
    rules: {},
}

.stylelintrc.js 文件

module.exports = {
    extends: [
        'stylelint-config-standard-scss',
    ],
    rules: {
        indentation: 4,
        'media-feature-range-notation': null,
        'alpha-value-notation': ['number'],
        'color-function-notation': ['legacy'],
        'no-descending-specificity': null,
        'font-family-no-missing-generic-family-keyword': null,
        'selector-type-no-unknown': null,
        'at-rule-no-unknown': null,
        'no-duplicate-selectors': null,
        'no-empty-source': null,
        'selector-class-pattern': null,
        'selector-pseudo-class-no-unknown': [
            true,
            { ignorePseudoClasses: ['global', 'deep'] },
        ],
        'scss/at-rule-no-unknown': [
            true,
            {
                ignoreAtRules: ['tailwind'],
            },
        ],
    },
};

踩坑

忽略 .vue 文件中的 HTML 模板验证规则无效

举个例子,如果你将 HTML 模板每行的代码文本长度设为 100,当超过这个长度后 eslint 将会报错。此时如果你还是想超过这个长度,可以选择忽略这个规则:

/* eslint-disable max-len */

注意,以上这行忽略验证的代码是不会生效的,因为这个注释是 JavaScript 注释,我们需要将注释改为 HTML 格式,这样忽略验证才会生效:

<!-- eslint-disable max-len -->

总结

这样配置完成之后,基本上 vue3 项目里的代码都能格式化了(css js html 及各种衍生代码)。

为了不让大家再次踩坑,我已经将配置好的项目 demo 上传到 github 了,有需要直接克隆项目就行。

项目地址: github.com/woai3c/vite…

欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边,抽奖详情见活动文章