vue3+Vite+TS项目,配置ESlint和Prettier

慈云数据 2024-04-27 技术支持 67 0

创建vue3项目

实操过的有两种方式

  • 1.vue脚手架
  • 2.vite(推荐,也是尤大大团队研发)

    具体怎么新建一个vue3项目就不多讲了,可以按照官方文档来

    创建后的文件目录长这样

    在这里插入图片描述

    多提一句,vite也会随着时间不断迭代,后续项目结构可能还会发生变化,当前使用的vue版本

    和vite版本也一并贴出来

    在这里插入图片描述

    下面进入正题,为项目配置ESLint+Prettier

    ESLint

    1.ESLint介绍

    是一个用于检测 ECMAScript/JavaScript 代码中的潜在问题和错误的工具,旨在使代码更一致并避免错误。它可以帮助开发者检测代码中的潜在问题,提高代码质量。

    2.使用前提

    必须安装Node.js(^12.22.0、 ^14.17.0 或>=16.0.0)

    3.安装ESLint

    方式一:以问题的形式,根据用户选择配置属性

    使用以下命令安装和配置 ESLint :

    npm init @eslint/config
    # or
    yarn create @eslint/config
    # or
    pnpm create @eslint/config
    

    注意:运行以上命令是假设您已经有了一个package.json文件。如果没有,请确保事先运行pnpm init、npm init或yarn init。

    按照提示步骤一步一步选择, 回车即可:

    使用ESLint做什么? 建议选择第三个, 检查语法, 发现问题, 强制代码风格

    ? How would you like to use ESLint? …
      To check syntax only
      To check syntax and find problems
    ❯ To check syntax, find problems, and enforce code style
    

    项目模块类型? 普遍使用的 import/export 建议选择第一个

    ? What type of modules does your project use? …
    ❯ JavaScript modules (import/export)
      CommonJS (require/exports)
      None of these
    

    项目用的啥框架? 果断Vue.js(vite也可以搭建React,牛啊)

    ? Which framework does your project use? …
      React
    ❯ Vue.js
      None of these
    

    项目中使用 TypeScript? 根据自己项目情况选择(我是用到了,配置文件中有TS的部分)

    ? Does your project use TypeScript? › No / Yes
    

    代码运行环境? 支持多选,按空格选择/取消选择,建议全选上

    ? Where does your code run? …  (Press  to select,  to toggle all,  to invert selection)
    ✔ Browser
    ✔ Node
    

    选择代码风格? popular style里边没有 prettier ,建议使用回答问题来自定义代码风格,第二个

    ? How would you like to define a style for your project? …
      Use a popular style guide
    ❯ Answer questions about your style
    

    ESLint 的配置文件格式?看个人习惯,建议选择 JavaScript, 原因可以在 js 文件中写条件判断语句来根据开发或生产环境开关 ESLint 规则

    ? What format do you want your config file to be in? …
    ❯ JavaScript
      YAML
      JSON
    

    用啥缩进? 看个人习惯,我习惯spaces,选择空格的话默认是4个空格,习惯用2个空格的后边生成的配置中可以改成2个空格

    ? What style of indentation do you use? …
      Tabs
    ❯ Spaces
    

    字符串使用双引号还是单引号? 看个人习惯

    ? What quotes do you use for strings? …
    ❯ Double
      Single
    

    用哪种结束符? Windows是CRLF, Unix是LF, 我选Unix

    ? What line endings do you use? …
    ❯ Unix
      Windows
    

    用分号吗? 看个人习惯,我不喜欢分号,选的No

    ? Do you require semicolons? › No / Yes
    

    检查到我没有安装ESLint, 是否马上安装? 安装 eslint 和 eslint-plugin-vue, 选择 Yes

    Local ESLint installation not found.
    The config that you've selected requires the following dependencies:
    eslint-plugin-vue@latest eslint@latest
    ? Would you like to install them now? › No / Yes
    

    选择您使用的包管理器? 看个人习惯

    ? Which package manager do you want to use? …
      npm
    ❯ yarn
      pnpm
    

    回车确认, 开始安装…

    ✔ How would you like to use ESLint? · style
    ✔ What type of modules does your project use? · esm
    ✔ Which framework does your project use? · vue
    ✔ Does your project use TypeScript? · No / Yes
    ✔ Where does your code run? · browser, node
    ✔ How would you like to define a style for your project? · prompt
    ✔ What format do you want your config file to be in? · JavaScript
    ✔ What style of indentation do you use? · 4
    ✔ What quotes do you use for strings? · double
    ✔ What line endings do you use? · unix
    ✔ Do you require semicolons? · No / Yes
    Local ESLint installation not found.
    The config that you've selected requires the following dependencies:
    eslint-plugin-vue@latest eslint@latest
    ✔ Would you like to install them now? · No / Yes
    ✔ Which package manager do you want to use? · yarn
    Installing eslint-plugin-vue@latest, eslint@latest
    ...
    ...
    Done in 27.9s
    Successfully created .eslintrc.js file in /code/vue3.0-vite
    

    在项目的 package.json 文件中查看 devDependencies增加了 eslint 和 eslint-plugin-vue 在项目根目录生成了.eslintrc.cjs 配置文件,打开文件找到 rules 把 indent 规则里边的 4 改成 2, 代码缩进就是 2 个空格了

    在运行以上命令之后,目录中会有一个.eslintrc.{js,yml,json}文件。我选择使用的是JavaScript文件, 文件内容是这样的:

    module.exports = {
      env: {
        browser: true,
        es2021: true,
        node: true,
      },
      extends: [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:vue/vue3-essential"
      ],
      overrides: [
        {
          env: {
            node: true,
          },
          files: [".eslintrc.{js,cjs}"],
          parserOptions: {
            sourceType: "script",
          },
        },
      ],
      parserOptions: {
        ecmaVersion: "latest",
        parser: "@typescript-eslint/parser",
        sourceType: "module",
      },
      plugins: ["@typescript-eslint", "vue"],
      rules: {
        indent: ["error", 2],
        "linebreak-style": ["error", "unix"],
        quotes: ["error", "double"],
        semi: ["error", "never"],
      },
    }
    

    方式二: 手动设置

    可以在项目中手动设置ESLint。

    注意: 在开始之前,您必须已经有一个package.json文件。如果没有,请确保预先运行pnpm init, npm init或yarn init来创建文件

    1. 使用以下命令手动安装ESLint 和 Vue插件
    npm install eslint@latest eslint-plugin-vue@latest -D
    # or 
    yarn add eslint@latest eslint-plugin-vue@latest -D
    # or
    pnpm add eslint@latest eslint-plugin-vue@latest -D
    
    1. 项目根目录中添加一个.eslintrc.js配置文件
    # Create JavaScript configuration file
    touch .eslintrc.js
    
    1. 在编辑器中打开.eslintrc.js配置文件进行自定义配置
    // .eslintrc.js
    module.exports = {
      env: {
        browser: true,
        es2021: true,
        node: true,
      },
      extends: ["eslint:recommended", "plugin:vue/vue3-essential"],
      overrides: [],
      parserOptions: {
        ecmaVersion: "latest",
        sourceType: "module",
      },
      plugins: ["vue"],
      rules: {
        indent: ["error", 2],
        "linebreak-style": ["error", "unix"],
        quotes: ["error", "double"],
        semi: ["error", "always"],
      },
    };
    

    以上步骤完成 ESLint 就安装上了

    然后在项目根目录添加.eslintignore文件, 忽略不想让ESLint检查的文件夹和文件

    touch .eslintignore
    

    想忽略的全往里边列就行了, 举个例子 :

    *.sh
    *.md
    *.woff
    *.ttf
    *.yaml
    .vscode
    .idea
    node_modules
    dist
    public
    docs
    .husky
    .eslintrc.js
    # Allowlist 'test.js' in the '.build' folder
    # But do not allow anything else in the '.build' folder to be linted
    !.build
    .build/*
    !.build/test.js
    

    Prettier

    1.Prettier介绍

    • 一个“有态度”的代码格式化工具
    • 支持大量编程语言
    • 已集成到大多数编辑器中
    • 几乎不需要设置参数

      为什么使用Prettier?

      • 按保存键时,代码就被格式化了
      • 代码评审时无须争论代码样式
      • 节省时间和精力

        2.安装Prettier

        先在本地安装Prettier

        npm install prettier@latest -D
        # or
        yarn add prettier@latest -D
        # or
        pnpm add prettier@latest -D
        

        然后,创建一个空的配置文件,让编辑器和其他工具知道您正在使用Prettier:

        echo {} > .prettierrc.json
        

        在配置文件中增加如下内容:

        // .prettierrc.json 规则配置, 后边将配置ESLint使用Prettier规则检查代码,以及怎么解决二者规则冲突的问题
        {
          "useTabs": false,
          "tabWidth": 2,
          "jsxSingleQuote": false,
          "singleQuote": false,
          "endOfLine": "lf",
          "semi": true,
          "trailingComma": "es5"
        }
        

        以下是Prettier的部分规则(根据项目的具体要求配置)

        {
            /*  prettier的配置 */
            "printWidth": 100, // 超过最大值换行
            "tabWidth": 4, // 缩进字节数
            "useTabs": false, // 缩进不使用tab,使用空格
            "semi": true, // 句尾添加分号
            "singleQuote": true, // 使用单引号代替双引号
            "proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
            "arrowParens": "avoid", //  (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
            "bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
            "disableLanguages": ["vue"], // 不格式化vue文件,vue文件的格式化单独设置
            "endOfLine": "auto", // 结尾是 \n \r \n\r auto
            "eslintIntegration": false, //不让prettier使用eslint的代码格式进行校验
            "htmlWhitespaceSensitivity": "ignore",
            "ignorePath": ".prettierignore", // 不使用prettier格式化的文件填写在项目的.prettierignore文件中
            "jsxBracketSameLine": false, // 在jsx中把'>' 是否单独放一行
            "jsxSingleQuote": false, // 在jsx中使用单引号代替双引号
            "parser": "babylon", // 格式化的解析器,默认是babylon
            "requireConfig": false, // Require a 'prettierconfig' to format prettier
            "stylelintIntegration": false, //不让prettier使用stylelint的代码格式进行校验
            "trailingComma": "es5", // 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
            "tslintIntegration": false // 不让prettier使用tslint的代码格式进行校验
        }
        

        (可选)接下来,创建一个.prettierignore文件,让Prettier CLI和编辑器知道不格式化哪些文件。下面是一个例子:

        # Ignore artifacts:
        build
        coverage
        

        我没有创建.prettierignore文件, 感觉有.eslintignore就够了

        提示: 以.gitignore 和.eslintignore 为基础(如果你有)。

        现在,使用Prettier格式化所有文件:

        npx prettier --write .
        # or 只检查src下所有文件
        prettier --write --loglevel warn "src/**/*.{js,ts,json,tsx,css,less,vue,html,md}"
        

        小技巧:webstorm使用prettier,实现保存文件时自动执行Prettier格式化

        在这里插入图片描述

        配合ESLint使用, 解决二者规则冲突

        当 ESLint 的规则和 Prettier 的规则相冲突时,就会发现一个尴尬的问题,用Prettier来格式化代码,ESLint就会报错。

        与ESLint配合使用,请安装eslint-config-prettier,以使ESLint和Prettier彼此配合得很好。它关闭所有不必要的或可能与Prettier冲突的ESLint规则。具体步骤如下:

        # Install eslint-config-prettier
        npm install eslint-config-prettier@latest -D
        # or
        yarn add eslint-config-prettier@latest -D
        # or
        pnpm add eslint-config-prettier@latest -D
        

        修改.eslintrc.js

        module.exports = {
          // 在 extends 尾部加入 prettier 即可
          extends: [
            "eslint:recommended",
            "plugin:@typescript-eslint/recommended",
            "plugin:vue/vue3-essential",
            "prettier"
          ]
        };
        

        但是以上做法只是关闭了与Prettier相冲突的ESLint的规则, 而我们的目标是要让ESLint使用Prettier的规则去检查代码语法和风格等问题, 有办法, prettier官方有个插件eslint-plugin-prettier, 使用这个插件一步简单的配置就搞定:

        prettier官方推荐配置方法

        1.安装eslint-plugin-prettier和eslint-config-prettier

        npm install eslint-plugin-prettier@latest eslint-config-prettier@latest -D
        # or
        yarn add eslint-plugin-prettier@latest eslint-config-prettier@latest -D
        # or
        pnpm add eslint-plugin-prettier@latest eslint-config-prettier@latest -D
        

        2.在.eslintrc.js中添加plugin:prettier/recommended作为最后一个扩展

        module.exports = {
          // 在 extends 尾部增加 plugin:prettier/recommended
          extends: [
            "eslint:recommended",
            "plugin:@typescript-eslint/recommended",
            "plugin:vue/vue3-essential",
            "plugin:prettier/recommended",
          ],
        };
        

        plugin:prettier/recommended相当于以下配置:

        module.exports = {
          extends: ["prettier"],
          plugins: ["prettier"],
          rules: {
            "prettier/prettier": "error",
            "arrow-body-style": "off",
            "prefer-arrow-callback": "off",
          },
        };
        

        现在,修改后的eslintrc.js就可以让ESLint和Prettier配合工作了

        拓展:启动项目和打包代码时进行代码检查

        使用vite-plugin-eslint插件, 默认配置是如果检查有error类型的问题就启动或打包失败, warn类型的问题不影响启动和打包 开始配置:

        1.安装vite-plugin-eslint

        npm install vite-plugin-eslint@latest -D
        # or
        yarn add vite-plugin-eslint@latest -D
        # or
        pnpm add vite-plugin-eslint@latest -D
        

        2.在 vite 的配置文件中引入插件并配置到 plugins 中

        import { defineConfig } from "vite"
        import vue from "@vitejs/plugin-vue"
        import eslint from "vite-plugin-eslint"
        // https://vitejs.dev/config/
        export default defineConfig({
          plugins: [vue(), eslint({ lintOnStart: true, cache: false })],
        })
        

        拓展:覆盖 vue/multi-word-component-names 规则

        在这里插入图片描述

        这个规则要求组件名称要多个单词构成, 而我们当初写的时候没有注意这一点, 现在改成本太大了, 只能把这个规则给覆盖掉

        module.exports = {
          // .eslintrc.js 文件 overrides 部分
          overrides: [
            {
              files: ["src/**/*.vue"],
              rules: { "vue/multi-word-component-names": "off" },
            },
          ],
        };
        

        总结

        ESLint配置文件(需求不同,会有一些差异)

        // .eslintrc.js
        module.exports = {
          env: {
            browser: true,
            es2021: true,
            node: true,
          },
          extends: [
            "eslint:recommended",
            "plugin:@typescript-eslint/recommended",
            "plugin:vue/vue3-essential",
            "plugin:prettier/recommended",
          ],
          overrides: [
            {
              env: {
                node: true,
              },
              files: [".eslintrc.{js,cjs}"],
              parserOptions: {
                sourceType: "script",
              },
            },
            {
              files: ["src/**/*.vue"],
              // 关闭组件名需要多个单词组成的规则
              rules: { "vue/multi-word-component-names": "off" },
            },
          ],
          parserOptions: {
            ecmaVersion: "latest",
            parser: "@typescript-eslint/parser",
            sourceType: "module",
          },
          plugins: ["@typescript-eslint", "vue"],
          rules: {
            // 解决ESLint和Prettier的switch/case缩进冲突
            indent: ["error", 2, { SwitchCase: 1 }],
            "no-unused-vars": "off",
            // vite打包时自动去除console和debugger,所以这里直接关掉检查
            "no-console": "off",
            "no-debugger": "off",
            // 允许catch空着
            "no-empty": ["error", { allowEmptyCatch: true }],
            "linebreak-style": ["error", "unix"],
            quotes: ["error", "double"],
            semi: ["error", "never"],
          },
        };
        

        Prettier配置文件

        // .prettierrc.json
        {
          "useTabs": false,
          "tabWidth": 2,
          "jsxSingleQuote": false,
          "singleQuote": false,
          "endOfLine": "lf",
          "semi": false,
          "trailingComma": "es5"
        }
        

        安装的依赖包

        // package.json 中新增了如下依赖包
        {
          "devDependencies": {
            "@typescript-eslint/eslint-plugin": "^7.3.1",
            "@typescript-eslint/parser": "^7.3.1",
            "eslint": "^8.57.0",
            "eslint-config-prettier": "^9.1.0",
            "eslint-plugin-prettier": "^5.1.3",
            "eslint-plugin-vue": "^9.23.0",
            "prettier": "^3.2.5",
            // vite插件
            "vite-plugin-eslint": "^1.8.1"
          }
        }
        

        结束

微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon