ToB企服应用市场:ToB评测及商务社交产业平台

标题: vue3+Vite+TS项目,配置ESlint和Prettier [打印本页]

作者: 愛在花開的季節    时间: 2024-6-14 22:13
标题: vue3+Vite+TS项目,配置ESlint和Prettier
创建vue3项目

实操过的有两种方式

具体怎么新建一个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 :
  1. npm init @eslint/config
  2. # or
  3. yarn create @eslint/config
  4. # or
  5. pnpm create @eslint/config
复制代码
  注意:运行以上命令是假设您已经有了一个package.json文件。如果没有,请确保事先运行pnpm init、npm init或yarn init。
  按照提示步调一步一步选择, 回车即可:
使用ESLint做什么? 发起选择第三个, 查抄语法, 发现题目, 强制代码风格
  1. ? How would you like to use ESLint? …
  2.   To check syntax only
  3.   To check syntax and find problems
  4. ❯ To check syntax, find problems, and enforce code style
复制代码
项目模块范例? 广泛使用的 import/export 发起选择第一个
  1. ? What type of modules does your project use? …
  2. ❯ JavaScript modules (import/export)
  3.   CommonJS (require/exports)
  4.   None of these
复制代码
项目用的啥框架? 果断Vue.js(vite也可以搭建React,牛啊)
  1. ? Which framework does your project use? …
  2.   React
  3. ❯ Vue.js
  4.   None of these
复制代码
项目中使用 TypeScript? 根据本身项目环境选择(我是用到了,配置文件中有TS的部门
  1. ? Does your project use TypeScript? › No / Yes
复制代码
代码运行环境? 支持多选,按空格选择/取消选择,发起全选上
  1. ? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
  2. ✔ Browser
  3. ✔ Node
复制代码
选择代码风格? popular style里边没有 prettier ,发起使用回答题目来自界说代码风格,第二个
  1. ? How would you like to define a style for your project? …
  2.   Use a popular style guide
  3. ❯ Answer questions about your style
复制代码
ESLint 的配置文件格式?看个人风俗,发起选择 JavaScript, 原因可以在 js 文件中写条件判断语句来根据开辟或生产环境开关 ESLint 规则
  1. ? What format do you want your config file to be in? …
  2. ❯ JavaScript
  3.   YAML
  4.   JSON
复制代码
用啥缩进? 看个人风俗,我风俗spaces,选择空格的话默认是4个空格,风俗用2个空格的后边生成的配置中可以改成2个空格
  1. ? What style of indentation do you use? …
  2.   Tabs
  3. ❯ Spaces
复制代码
字符串使用双引号还是单引号? 看个人风俗
  1. ? What quotes do you use for strings? …
  2. ❯ Double
  3.   Single
复制代码
用哪种结束符? Windows是CRLF, Unix是LF, 我选Unix
  1. ? What line endings do you use? …
  2. ❯ Unix
  3.   Windows
复制代码
用分号吗? 看个人风俗,我不喜欢分号,选的No
  1. ? Do you require semicolons? › No / Yes
复制代码
查抄到我没有安装ESLint, 是否马上安装? 安装 eslint 和 eslint-plugin-vue, 选择 Yes
  1. Local ESLint installation not found.
  2. The config that you've selected requires the following dependencies:
  3. eslint-plugin-vue@latest eslint@latest
  4. ? Would you like to install them now? › No / Yes
复制代码
选择您使用的包管理器? 看个人风俗
  1. ? Which package manager do you want to use? …
  2.   npm
  3. ❯ yarn
  4.   pnpm
复制代码
回车确认, 开始安装…
  1. ✔ How would you like to use ESLint? · style
  2. ✔ What type of modules does your project use? · esm
  3. ✔ Which framework does your project use? · vue
  4. ✔ Does your project use TypeScript? · No / Yes
  5. ✔ Where does your code run? · browser, node
  6. ✔ How would you like to define a style for your project? · prompt
  7. ✔ What format do you want your config file to be in? · JavaScript
  8. ✔ What style of indentation do you use? · 4
  9. ✔ What quotes do you use for strings? · double
  10. ✔ What line endings do you use? · unix
  11. ✔ Do you require semicolons? · No / Yes
  12. Local ESLint installation not found.
  13. The config that you've selected requires the following dependencies:
  14. eslint-plugin-vue@latest eslint@latest
  15. ✔ Would you like to install them now? · No / Yes
  16. ✔ Which package manager do you want to use? · yarn
  17. Installing eslint-plugin-vue@latest, eslint@latest
  18. ...
  19. ...
  20. Done in 27.9s
  21. 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文件, 文件内容是这样的:
  1. module.exports = {
  2.   env: {
  3.     browser: true,
  4.     es2021: true,
  5.     node: true,
  6.   },
  7.   extends: [
  8.     "eslint:recommended",
  9.     "plugin:@typescript-eslint/recommended",
  10.     "plugin:vue/vue3-essential"
  11.   ],
  12.   overrides: [
  13.     {
  14.       env: {
  15.         node: true,
  16.       },
  17.       files: [".eslintrc.{js,cjs}"],
  18.       parserOptions: {
  19.         sourceType: "script",
  20.       },
  21.     },
  22.   ],
  23.   parserOptions: {
  24.     ecmaVersion: "latest",
  25.     parser: "@typescript-eslint/parser",
  26.     sourceType: "module",
  27.   },
  28.   plugins: ["@typescript-eslint", "vue"],
  29.   rules: {
  30.     indent: ["error", 2],
  31.     "linebreak-style": ["error", "unix"],
  32.     quotes: ["error", "double"],
  33.     semi: ["error", "never"],
  34.   },
  35. }
复制代码
方式二: 手动设置
可以在项目中手动设置ESLint。
   注意: 在开始之前,您必须已经有一个package.json文件。如果没有,请确保预先运行pnpm init, npm init或yarn init来创建文件。
  
  1. npm install eslint@latest eslint-plugin-vue@latest -D
  2. # or
  3. yarn add eslint@latest eslint-plugin-vue@latest -D
  4. # or
  5. pnpm add eslint@latest eslint-plugin-vue@latest -D
复制代码
  1. # Create JavaScript configuration file
  2. touch .eslintrc.js
复制代码
  1. // .eslintrc.js
  2. module.exports = {
  3.   env: {
  4.     browser: true,
  5.     es2021: true,
  6.     node: true,
  7.   },
  8.   extends: ["eslint:recommended", "plugin:vue/vue3-essential"],
  9.   overrides: [],
  10.   parserOptions: {
  11.     ecmaVersion: "latest",
  12.     sourceType: "module",
  13.   },
  14.   plugins: ["vue"],
  15.   rules: {
  16.     indent: ["error", 2],
  17.     "linebreak-style": ["error", "unix"],
  18.     quotes: ["error", "double"],
  19.     semi: ["error", "always"],
  20.   },
  21. };
复制代码
以上步调完成 ESLint 就安装上了
然后在项目根目次添加.eslintignore文件, 忽略不想让ESLint查抄的文件夹和文件
  1. touch .eslintignore
复制代码
想忽略的全往里边列就行了, 举个例子 :
  1. *.sh
  2. *.md
  3. *.woff
  4. *.ttf
  5. *.yaml
  6. .vscode
  7. .idea
  8. node_modules
  9. dist
  10. public
  11. docs
  12. .husky
  13. .eslintrc.js
  14. # Allowlist 'test.js' in the '.build' folder
  15. # But do not allow anything else in the '.build' folder to be linted
  16. !.build
  17. .build/*
  18. !.build/test.js
复制代码
Prettier

1.Prettier介绍


为什么使用Prettier?

2.安装Prettier

先在本地安装Prettier
  1. npm install prettier@latest -D
  2. # or
  3. yarn add prettier@latest -D
  4. # or
  5. pnpm add prettier@latest -D
复制代码
然后,创建一个空的配置文件,让编辑器和其他工具知道您正在使用Prettier:
  1. echo {} > .prettierrc.json
复制代码
在配置文件中增长如下内容:
  1. // .prettierrc.json 规则配置, 后边将配置ESLint使用Prettier规则检查代码,以及怎么解决二者规则冲突的问题
  2. {
  3.   "useTabs": false,
  4.   "tabWidth": 2,
  5.   "jsxSingleQuote": false,
  6.   "singleQuote": false,
  7.   "endOfLine": "lf",
  8.   "semi": true,
  9.   "trailingComma": "es5"
  10. }
复制代码
以下是Prettier的部门规则(根据项目标具体要求配置)
  1. {
  2.     /*  prettier的配置 */
  3.     "printWidth": 100, // 超过最大值换行
  4.     "tabWidth": 4, // 缩进字节数
  5.     "useTabs": false, // 缩进不使用tab,使用空格
  6.     "semi": true, // 句尾添加分号
  7.     "singleQuote": true, // 使用单引号代替双引号
  8.     "proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
  9.     "arrowParens": "avoid", //  (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
  10.     "bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
  11.     "disableLanguages": ["vue"], // 不格式化vue文件,vue文件的格式化单独设置
  12.     "endOfLine": "auto", // 结尾是 \n \r \n\r auto
  13.     "eslintIntegration": false, //不让prettier使用eslint的代码格式进行校验
  14.     "htmlWhitespaceSensitivity": "ignore",
  15.     "ignorePath": ".prettierignore", // 不使用prettier格式化的文件填写在项目的.prettierignore文件中
  16.     "jsxBracketSameLine": false, // 在jsx中把'>' 是否单独放一行
  17.     "jsxSingleQuote": false, // 在jsx中使用单引号代替双引号
  18.     "parser": "babylon", // 格式化的解析器,默认是babylon
  19.     "requireConfig": false, // Require a 'prettierconfig' to format prettier
  20.     "stylelintIntegration": false, //不让prettier使用stylelint的代码格式进行校验
  21.     "trailingComma": "es5", // 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
  22.     "tslintIntegration": false // 不让prettier使用tslint的代码格式进行校验
  23. }
复制代码
(可选)接下来,创建一个.prettierignore文件,让Prettier CLI和编辑器知道不格式化哪些文件。下面是一个例子:
  1. # Ignore artifacts:
  2. build
  3. coverage
复制代码
我没有创建.prettierignore文件, 感觉有.eslintignore就够了
   提示: 以.gitignore 和.eslintignore 为基础(如果你有)。
  现在,使用Prettier格式化全部文件:
  1. npx prettier --write .
  2. # or 只检查src下所有文件
  3. 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规则。具体步调如下:
  1. # Install eslint-config-prettier
  2. npm install eslint-config-prettier@latest -D
  3. # or
  4. yarn add eslint-config-prettier@latest -D
  5. # or
  6. pnpm add eslint-config-prettier@latest -D
复制代码
修改.eslintrc.js
  1. module.exports = {
  2.   // 在 extends 尾部加入 prettier 即可
  3.   extends: [
  4.     "eslint:recommended",
  5.     "plugin:@typescript-eslint/recommended",
  6.     "plugin:vue/vue3-essential",
  7.     "prettier"
  8.   ]
  9. };
复制代码
但是以上做法只是关闭了与Prettier相冲突的ESLint的规则, 而我们的目标是要让ESLint使用Prettier的规则去查抄代码语法和风格等题目, 有办法, prettier官方有个插件eslint-plugin-prettier, 使用这个插件一步简单的配置就搞定:
prettier官方保举配置方法
1.安装eslint-plugin-prettier和eslint-config-prettier
  1. npm install eslint-plugin-prettier@latest eslint-config-prettier@latest -D
  2. # or
  3. yarn add eslint-plugin-prettier@latest eslint-config-prettier@latest -D
  4. # or
  5. pnpm add eslint-plugin-prettier@latest eslint-config-prettier@latest -D
复制代码
2.在.eslintrc.js中添加plugin:prettier/recommended作为末了一个扩展
  1. module.exports = {
  2.   // 在 extends 尾部增加 plugin:prettier/recommended
  3.   extends: [
  4.     "eslint:recommended",
  5.     "plugin:@typescript-eslint/recommended",
  6.     "plugin:vue/vue3-essential",
  7.     "plugin:prettier/recommended",
  8.   ],
  9. };
复制代码
plugin:prettier/recommended相当于以下配置:
  1. module.exports = {
  2.   extends: ["prettier"],
  3.   plugins: ["prettier"],
  4.   rules: {
  5.     "prettier/prettier": "error",
  6.     "arrow-body-style": "off",
  7.     "prefer-arrow-callback": "off",
  8.   },
  9. };
复制代码
现在,修改后的eslintrc.js就可以让ESLint和Prettier配合工作了
拓展:启动项目和打包代码时进行代码查抄

使用vite-plugin-eslint插件, 默认配置是如果查抄有error范例的题目就启动或打包失败, warn范例的题目不影响启动和打包 开始配置:
1.安装vite-plugin-eslint
  1. npm install vite-plugin-eslint@latest -D
  2. # or
  3. yarn add vite-plugin-eslint@latest -D
  4. # or
  5. pnpm add vite-plugin-eslint@latest -D
复制代码
2.在 vite 的配置文件中引入插件并配置到 plugins 中
  1. import { defineConfig } from "vite"
  2. import vue from "@vitejs/plugin-vue"
  3. import eslint from "vite-plugin-eslint"
  4. // https://vitejs.dev/config/
  5. export default defineConfig({
  6.   plugins: [vue(), eslint({ lintOnStart: true, cache: false })],
  7. })
复制代码
拓展:覆盖 vue/multi-word-component-names 规则


这个规则要求组件名称要多个单词构成, 而我们当初写的时候没有注意这一点, 现在改成本太大了, 只能把这个规则给覆盖掉
  1. module.exports = {
  2.   // .eslintrc.js 文件 overrides 部分
  3.   overrides: [
  4.     {
  5.       files: ["src/**/*.vue"],
  6.       rules: { "vue/multi-word-component-names": "off" },
  7.     },
  8.   ],
  9. };
复制代码
总结

ESLint配置文件(需求不同,会有一些差别)
  1. // .eslintrc.js
  2. module.exports = {
  3.   env: {
  4.     browser: true,
  5.     es2021: true,
  6.     node: true,
  7.   },
  8.   extends: [
  9.     "eslint:recommended",
  10.     "plugin:@typescript-eslint/recommended",
  11.     "plugin:vue/vue3-essential",
  12.     "plugin:prettier/recommended",
  13.   ],
  14.   overrides: [
  15.     {
  16.       env: {
  17.         node: true,
  18.       },
  19.       files: [".eslintrc.{js,cjs}"],
  20.       parserOptions: {
  21.         sourceType: "script",
  22.       },
  23.     },
  24.     {
  25.       files: ["src/**/*.vue"],
  26.       // 关闭组件名需要多个单词组成的规则
  27.       rules: { "vue/multi-word-component-names": "off" },
  28.     },
  29.   ],
  30.   parserOptions: {
  31.     ecmaVersion: "latest",
  32.     parser: "@typescript-eslint/parser",
  33.     sourceType: "module",
  34.   },
  35.   plugins: ["@typescript-eslint", "vue"],
  36.   rules: {
  37.     // 解决ESLint和Prettier的switch/case缩进冲突
  38.     indent: ["error", 2, { SwitchCase: 1 }],
  39.     "no-unused-vars": "off",
  40.     // vite打包时自动去除console和debugger,所以这里直接关掉检查
  41.     "no-console": "off",
  42.     "no-debugger": "off",
  43.     // 允许catch空着
  44.     "no-empty": ["error", { allowEmptyCatch: true }],
  45.     "linebreak-style": ["error", "unix"],
  46.     quotes: ["error", "double"],
  47.     semi: ["error", "never"],
  48.   },
  49. };
复制代码
Prettier配置文件
  1. // .prettierrc.json
  2. {
  3.   "useTabs": false,
  4.   "tabWidth": 2,
  5.   "jsxSingleQuote": false,
  6.   "singleQuote": false,
  7.   "endOfLine": "lf",
  8.   "semi": false,
  9.   "trailingComma": "es5"
  10. }
复制代码
安装的依赖包
  1. // package.json 中新增了如下依赖包
  2. {
  3.   "devDependencies": {
  4.     "@typescript-eslint/eslint-plugin": "^7.3.1",
  5.     "@typescript-eslint/parser": "^7.3.1",
  6.     "eslint": "^8.57.0",
  7.     "eslint-config-prettier": "^9.1.0",
  8.     "eslint-plugin-prettier": "^5.1.3",
  9.     "eslint-plugin-vue": "^9.23.0",
  10.     "prettier": "^3.2.5",
  11.     // vite插件
  12.     "vite-plugin-eslint": "^1.8.1"
  13.   }
  14. }
复制代码
结束

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4