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

创建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 <space> to select, <a> to toggle all, <i> 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"
  }
}

结束

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/494851.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

方格分割(蓝桥杯)

文章目录 方格分割题目描述答案&#xff1a;509思路dfs 方格分割 题目描述 本题为填空题&#xff0c;只需要算出结果后&#xff0c;在代码中使用输出语句将所填结果输出即可。 6x6的方格&#xff0c;沿着格子的边线剪开成两部分。 要求这两部分的形状完全相同。 如下就是三…

蓝桥杯基础练习汇总详细解析(三)——字母图形、01字符串、闰年判断(详细解题思路、代码实现、Python)

试题 基础练习 字母图形 提交此题 评测记录 资源限制 内存限制&#xff1a;256.0MB C/C时间限制&#xff1a;1.0s Java时间限制&#xff1a;3.0s Python时间限制&#xff1a;5.0s 问题描述 利用字母可以组成一些美丽的图形&#xff0c;下面给出了一个例子&#…

汇编语言学习记录 01

目录 VScode配置调试环境 Debug的主要命令 简单写个Hello World VScode配置调试环境 没有IDE真的蛮难受的 安装插件TASM/MASM 右键扩展设置&#xff0c;选择Assembler&#xff1a;MASM 右键调试即可开始 Debug的主要命令 R-查看和修改寄存器 D-查看内存单元 E-修改内…

SAP系统如何使用中间数据库与其它系统进行数据交互

SAP系统与外部系统之间进行数据交换和通信的接口方式有很多种,比如常用的接口技术有RFC、BAPI、ALE、Webservice、RESTful、中间数据库等等,不同的接口形式具有不同的特点和适用场景,可以根据具体需求选择合适的接口形式来实现系统间的数据交互。 前面文章中已介绍Webservi…

2024年腾讯云4核8G服务器多少钱一年?买1年送3个月

2024年腾讯云4核8G服务器租用优惠价格&#xff1a;轻量应用服务器4核8G12M带宽646元15个月&#xff0c;CVM云服务器S5实例优惠价格1437.24元买一年送3个月&#xff0c;腾讯云4核8G服务器活动页面 txybk.com/go/txy 活动链接打开如下图&#xff1a; 腾讯云4核8G服务器优惠价格 轻…

SOC子模块--Timer

作用 Timer 是片内集成的通用定时器&#xff0c;能够向系统提供定时中断&#xff0c;也可以通过外部时钟进行定时计数&#xff1b; 工作模式 重启计数模式&#xff1a; 当通道使能后计数器锁存加载计数寄存器的值&#xff0c;然后在系统时钟的驱动下递减计数。当计数到零时…

信息系统项目管理师——第9章项目范围管理(重要)

本章属于10大管理知识领域&#xff0c;选择、案例、论文都会考。选择题考大概3分&#xff0c;案例题考的比较多&#xff0c;需要重点记录&#xff0c;论文也考的比较多&#xff0c;建议作为第二梯队准备。 1.管理基础 1.1 产品范围和项目范围 产品范围:指某项产品、服务或成…

Yarn资源调度器

目录 写在前面一、yarn资源调度器1.1 Yarn基础架构1.2 Yarn工作机制1.3 作业提交全过程1.3.1 作业提交1.3.2 作业初始化1.3.3 任务分配1.3.4 任务运行1.3.5 进度和状态更新1.3.6 作业完成 1.4 Yarn调度器和调度算法1.4.1 先进先出调度器&#xff08;FIFO&#xff09;1.4.2 容量…

如何使用VS统计自己的代码量?

历经漫漫编程之路&#xff0c;此刻我们不妨回首细数&#xff0c;那已累积的无数行代码&#xff0c;它们如同一串串无声的脚印&#xff0c;记载着我们默默耕耘的点滴时光。每一行代码都是平凡努力的印记&#xff0c;见证了我们的执着与付出&#xff0c;也塑造了今天的我们。让这…

Pandas数据清洗

数据清洗是对一些没有用的数据进行处理的过程。很多数据集存在数据缺失、数据格式错误、数据错误或数据重复的情况&#xff0c;如果要使数据分析更加准确&#xff0c;就需要对这些没有用的数据进行处理。 这里使用的测试数据是clean-data.csv&#xff0c;如图3-10所示。这个表…

【二叉树】Leetcode 108. 将有序数组转换为二叉搜索树【简单】

将有序数组转换为二叉搜索树 给你一个整数数组 nums &#xff0c;其中元素已经按 升序 排列&#xff0c;请你将其转换为一棵 平衡二叉搜索树。 示例1&#xff1a; 输入&#xff1a;nums [-10,-3,0,5,9] 输出&#xff1a;[0,-3,9,-10,null,5] 解释&#xff1a;[0,-10,5,null…

npm淘宝镜像源更新

目录 前情提要&#xff1a; 背景&#xff1a; 镜像源更新&#xff1a; 清楚缓存&#xff1a; 直接切换镜像源&#xff1a; 补充&#xff1a; 错误解释&#xff1a; 解决方法&#xff1a; 前情提要&#xff1a; 2024 /1 /22 &#xff0c;registry.npm.taobao.org淘宝镜像源的SSL…

基于java实现的高校二手交易平台

开发语言&#xff1a;Java 框架&#xff1a;ssm 技术&#xff1a;JSP JDK版本&#xff1a;JDK1.8 服务器&#xff1a;tomcat7 数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09; 数据库工具&#xff1a;Navicat11 开发软件&#xff1a;eclipse/myeclip…

【uniapp】uniapp实现免密登录

文章目录 一、概要二、整体架构流程三、技术名词解释四 、技术细节1.存取token有效期&#xff1f;2.使用setStorageSync而不使用setStorage&#xff1f;3.使用onLaunch而不使用全局路由&#xff1f; 一、概要 打开一个网页或小程序的时候&#xff0c;我们有时候会自动进入主页…

【JAVA】多态

去完成某个行为&#xff0c;当不同的对象去完成时会产生出不同 的状 态。 比如吃东西 猫吃的是猫粮&#xff0c;狗吃的是狗粮 多态实现条件 1. 必须在继承体系下 2. 子类必须要对父类中方法进行重写 3. 通过父类的引用调用重写的方法 多态体现&#xff1a;在代码运行时…

【Spring Boot 源码学习】共享 MetadataReaderFactory 上下文初始化器

《Spring Boot 源码学习系列》 共享 MetadataReaderFactory 上下文初始化器 一、引言二、往期内容三、主要内容3.1 源码初识3.2 CachingMetadataReaderFactoryPostProcessor3.2.1 register 方法3.2.1 configureConfigurationClassPostProcessor 方法 3.3 ConfigurationClassPos…

uniApp使用XR-Frame创建3D场景(4)金属度和粗糙度

上一篇讲解了如何在uniApp中创建xr-frame子组件并创建简单的3D场景。 这一篇我们讲解xr-frame中关于mesh网格材质的金属度和粗糙度的设置。 1.先看源码 <xr-scene render-system"alpha:true" bind:ready"handleReady"> <xr-node visible"{…

面试知识汇总——JVM内存模型

JVM内存模型 线程独占&#xff1a;栈和本地方法栈、程序计数器&#xff1b;线程共享的是堆和方法区 栈&#xff1a;又叫方法栈&#xff0c;线程私有&#xff0c;线程执行方法都会创建一个栈阵&#xff0c;用来储存局部变量表&#xff0c;调用方法执行入栈&#xff0c;方法返回…

AJAX(二):axios 和 fetch函数发送AJAX请求、同源策略、 jsonp、CORS

一、各种发送AJAX请求 jquery基于回调函数&#xff0c;axios基于promise 1.axios发送AJAX请求!!! axios (v1.5.0) - Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 Node.js 中。 | BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务 服务器&#xff1a; app.…

Linux 系统 docker搭建LNMP环境

1、安装nginx docker pull nginx (默认安装的是最新版本) 2、运行nginx docker run --name nginx -p 80:80 -d nginx:latest 备注&#xff1a;--name nginx 表示容器名为 nginx -d 表示后台运行 -p 80:80 表示把本地80端口绑定到Nginx服务端的 80端口 nginx:lates…
最新文章