WS 中 vite 的自动格式化代码规范

1,630 阅读7分钟

一向喜欢 VSCode 的小编最近也踏上了 WebStorm 的不归路,不得不说 WebStorm 强大到令人惊叹,往期的 VSCode格式化代码规范 在这里哦

这期我们来聊一下在 WebStorm 中用 Vite 快速搭建 vue3 的项目怎样使用 prettier 和 ESLint 做到自动格式化吧~

点这里免费申请 WebStorm 的开源许可证

一. 使用 ESLint 检测工具

1. 创建项目 这里是已经安装过 pnpm 和 vite 的

执行命令 pnpm create vite

√ Project name: ... vite-project
√ Select a framework: » Vue
√ Select a variant: » TypeScript

Done. Now run:

  cd vite-project
  pnpm install
  pnpm run dev

这里我们使用 ts 创建 vue3 的项目

2. 像 VSCode 需要安装 ESLint 插件一样,在 ws 中则需要进行一些配置

webstorm中eslint的配置.jpg

3. 安装Eslint

pnpm add eslint -D

4. 初始化 ESLint 配置

npx eslint --init
You can also run this command directly using 'npm init @eslint/config'.
? 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
-------------------------------------------------------------
? What type of modules does your project use? ... 
> JavaScript modules (import/export)              
  CommonJS (require/exports)                      
  None of these
-------------------------------------------------------------
? Which framework does your project use? ... 
  React                                      
> Vue.js                                     
  None of these
-------------------------------------------------------------
Does your project use TypeScript? » Yes
-------------------------------------------------------------
? Where does your code run? ...  (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser                                                                                             
√ Node 
-------------------------------------------------------------
? How would you like to define a style for your project? ... 
  Use a popular style guide                                  
> Answer questions about your style  
-------------------------------------------------------------
? What format do you want your config file to be in? ...         
> JavaScript                                                     
  YAML                                                           
  JSON
-------------------------------------------------------------
√ What style of indentation do you use? · tab
√ What quotes do you use for strings? · single
√ What line endings do you use? · unix
√ Do you require semicolons? · No 
-------------------------------------------------------------
eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
√ Would you like to install them now? · Yes
? Which package manager do you want to use? ...
  npm
  yarn
> pnpm

5. ESLint初始化完成

  • 安装完成后,在项目根目录会出现 .eslintrc.cjs 文件
  • 咦?为什么不是 js 文件呢
  • 仔细看看 package.json 文件
  • 发现了什么? "type": "module"
  • 好家伙,原来 vite 中默认是使用 CommonJS 的

我们来看看需要配置些什么:

module.exports = {
   "env": {
      "browser": true,
      "es2021": true,
      "node": true
   },
   "parser": "vue-eslint-parser", // 解析*.vue文件
   "extends": [
      "eslint-config-prettier",
      "eslint:recommended", // 使用推荐的eslint
      "plugin:vue/vue3-essential", // 使插件支持vue3
      "plugin:@typescript-eslint/recommended", // 使插件支持ts并使用推荐的ts-eslint
      "plugin:prettier/recommended" // 默认后面的插件会将前面的覆盖,解决prettier与eslint冲突
   ],
   "overrides": [
   ],
   "parserOptions": {
      "ecmaVersion": "latest",
      "parser": "@typescript-eslint/parser",
      "sourceType": "module"
   },
   "plugins": [
      "vue",
      "@typescript-eslint"
   ],
   "rules": {
      "indent": ["error", 2], // 两个空格的缩进
      // 指定行分隔符的格式为Unix内核的LF
      // 这可以避免我们在github/服务器等clone代码时分隔符格式不一样引起的错误
      "linebreak-style": [
         "error",
         "unix"
      ],
      // 使用单引号
      "quotes": [
         "error",
         "single"
      ],
      // 末尾不使用分号
      "semi": [
         "error",
         "never"
      ],
      "vue/multi-word-component-names": "off", // vue组件需要使用多个单词的名称
      "@typescript-eslint/no-explicit-any": "off", // ts: 不允许使用any
      "@typescript-eslint/no-non-null-assertion": "off" // ts: 不允许使用非空断言
   }
};

6. 安装vite-plugin-eslint

  • 这是 vite 中的插件,在 vite dev 环境下运行不符合 eslint 规范的代码,页面会报错
pnpm add vite-plugin-eslint -D

7. 安装eslint-parser

  • 默认情况下,ESLint 使用 Espree 作为其解析器。
  • @babel/eslint-parser 是一个与 ESLint 兼容的解析器,它允许 ESLint 在由 Babel 转换的源代码上运行。
pnpm add @babel/core @babel/eslint-parser -D

8. 配置vite.config.ts

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    eslintPlugin({
      include: ['src/**/*.ts', 'src/**/*.vue', 'src/*.ts', 'src/*.vue']
    })
  ],
  resolve: {
    // 配置别名
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
    // 结合 tsconfig.json 省略文件后缀名
    extensions: ['.mjs', '.ts', '.js', '.vue', '.jsx', '.tsx', '.json']
  }
})

以上就是小编的 eslint 的配置啦

二. 使用 Prettier 格式化代码工具

Prettier 是一款强大的代码格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等语言,基本上前端能用到的文件格式它都可以搞定,是当下最流行的代码格式化工具。

1. 安装 Prettier

pnpm add -D prettier
pnpm add -D eslint-config-prettier // eslint兼容的插件
pnpm add -D eslint-plugin-prettier // eslint的prettier

2. 配置 .prettierrc 文件:

  • useTabs:使用tab缩进还是空格缩进,选择false;
  • tabWidth:tab是空格的情况下,是几个空格,选择2个;
  • printWidth:当行字符的长度,推荐80,也有人喜欢100或者120;
  • singleQuote:使用单引号还是双引号,选择true,使用单引号;
  • trailingComma:在多行输入的尾逗号是否添加,设置为 none
  • semi:语句末尾是否要加分号,默认值true,选择false表示不加;
  • endOfLine:这是因为我们的空格是CRLF格式的,上传到Linux系统会被转换成LF格式,使用这个可以忽略每次在服务器将项目clone下来的一大堆格式问题(其实都是空格和换行符等引起的)
{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "none",
  "semi": false,
  "endOfLine": "auto"
}

3. 创建 .prettierignore 忽略文件

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*

4. WebStorm 需要安装 Prettier 的插件

webstorm安装prettier插件.jpg

5. 测试 Prettier 是否生效

  • 测试一:在代码中按下快捷键 Ctrl + Shift + Alt + p;
  • 测试二:在文件中点击鼠标右键,使用 Prettier 重新格式化
  • 测试三:配置一次性修改的命令;

在package.json中配置一个scripts:

"prettier": "prettier --write ."

6. 设置 WebStorm 自动保存并格式化

image.png

webstorm自动格式化1.jpg

webstorm自动格式化2.jpg

最后,别忘了重启IDE哦

以上就是 Prettier 和 ESLint 自动格式化代码规范的全部步骤啦

下面是 .eslintrc.cjs 的规则

"rules": {
        'semi': ['warn', 'never'],           // 禁止尾部使用分号
        'no-console': 'warn',                // 禁止出现console
        'no-debugger': 'warn',               // 禁止出现debugger
        'no-duplicate-case': 'warn',         // 禁止出现重复case
        'no-empty': 'warn',                  // 禁止出现空语句块
        'no-extra-parens': 'warn',           // 禁止不必要的括号
        'no-func-assign': 'warn',            // 禁止对Function声明重新赋值
        'no-unreachable': 'warn',            // 禁止出现[return|throw]之后的代码块
        'no-else-return': 'warn',            // 禁止if语句中return语句之后有else块
        'no-empty-function': 'warn',         // 禁止出现空的函数块
        'no-lone-blocks': 'warn',            // 禁用不必要的嵌套块
        'no-multi-spaces': 'warn',           // 禁止使用多个空格
        'no-redeclare': 'warn',              // 禁止多次声明同一变量
        'no-return-assign': 'warn',          // 禁止在return语句中使用赋值语句
        'no-return-await': 'warn',           // 禁用不必要的[return/await]
        'no-self-compare': 'warn',           // 禁止自身比较表达式
        'no-useless-catch': 'warn',          // 禁止不必要的catch子句
        'no-useless-return': 'warn',         // 禁止不必要的return语句
        'no-mixed-spaces-and-tabs': 'warn',  // 禁止空格和tab的混合缩进
        'no-multiple-empty-lines': 'warn',   // 禁止出现多行空行
        'no-trailing-spaces': 'warn',        // 禁止一行结束后面不要有空格
        'no-useless-call': 'warn',           // 禁止不必要的.call()和.apply()
        'no-var': 'warn',                    // 禁止出现var用let和const代替
        'no-delete-var': 'off',              // 允许出现delete变量的使用
        'no-shadow': 'off',                  // 允许变量声明与外层作用域的变量同名
        'dot-notation': 'warn',              // 要求尽可能地使用点号
        'default-case': 'warn',              // 要求switch语句中有default分支
        'eqeqeq': 'warn',                    // 要求使用 === 和 !==
        'curly': 'warn',                     // 要求所有控制语句使用一致的括号风格
        'space-before-blocks': 'warn',       // 要求在块之前使用一致的空格
        'space-in-parens': 'warn',           // 要求在圆括号内使用一致的空格
        'space-infix-ops': 'warn',           // 要求操作符周围有空格
        'space-unary-ops': 'warn',           // 要求在一元操作符前后使用一致的空格
        'switch-colon-spacing': 'warn',      // 要求在switch的冒号左右有空格
        'arrow-spacing': 'warn',             // 要求箭头函数的箭头前后使用一致的空格
        'array-bracket-spacing': 'warn',     // 要求数组方括号中使用一致的空格
        'brace-style': 'warn',               // 要求在代码块中使用一致的大括号风格
        'camelcase': 'warn',                 // 要求使用骆驼拼写法命名约定
        'indent': ['warn', 4],               // 要求使用JS一致缩进4个空格
        'max-depth': ['warn', 4],            // 要求可嵌套的块的最大深度4
        'max-statements': ['warn', 100],     // 要求函数块最多允许的的语句数量20
        'max-nested-callbacks': ['warn', 3], // 要求回调函数最大嵌套深度3
        'max-statements-per-line': ['warn', { max: 1 }],   // 要求每一行中所允许的最大语句数量
        "quotes": ["warn", "single", "avoid-escape"],      // 要求统一使用单引号符号
        "vue/require-default-prop": 0,                     // 关闭属性参数必须默认值
        "vue/singleline-html-element-content-newline": 0,  // 关闭单行元素必须换行符
        "vue/multiline-html-element-content-newline": 0,   // 关闭多行元素必须换行符
        // 要求每一行标签的最大属性不超五个
        'vue/max-attributes-per-line': ['warn', { singleline: 5 }],
        // 要求html标签的缩进为需要4个空格
        "vue/html-indent": ["warn", 4, {
            "attribute": 1,
            "baseIndent": 1,
            "closeBracket": 0,
            "alignAttributesVertically": true,
            "ignores": []
        }],
        // 取消关闭标签不能自闭合的限制设置
        "vue/html-self-closing": ["error", {              
            "html": {
                "void": "always",
                "normal": "never",
                "component": "always"
            },
            "svg": "always",
            "math": "always"
        }]   
    }
}