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

news2024/10/1 19:57:46

创建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.coloradmin.cn/o/1549706.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++入门】 初见,单推,与C++的第一次约会

关注小庄 顿顿解馋(ᕑᗢᓫ∗)˒ 引言&#xff1a;本篇博客我们开始与C的第一次约会&#xff0c;C是兼容c的&#xff0c;本篇博客我们将了解到C关键字有哪些&#xff0c;C命名空间&#xff0c;C输入与输出和缺省参数的内容&#xff0c;请放心食用 ~ 文章目录 一 &#x1f3e0; C…

github配置ssh

生成公钥 在电脑用户的目录下打开终端执行 ssh-keygen -t rsa: 执行完不要关 配置文件 看看用户的目录里 .ssh 目录&#xff1a; Host github.comHostname ssh.github.comPort 443配置公钥 复制 id_rsa.pub 文件里的内容 粘贴到 github上 连接密钥 回到刚才的终端…

【42 可视化大屏 | 某瓣电影Top250数据分析可视化大屏】

文章目录 &#x1f3f3;️‍&#x1f308; 1 普版大屏&#x1f3f3;️‍&#x1f308;2 Flask版大屏&#x1f3f3;️‍&#x1f308;3 FlaskMysql版大屏&#x1f3f3;️‍&#x1f308; 4. 可视化项目源码数据 大家好&#xff0c;我是 &#x1f449;【Python当打之年(点击跳转)…

学透Spring Boot — 创建一个简单Web应用

从今天开始&#xff0c;我们将开始学习一个新的系列&#xff0c;那就是在项目中用得非常广泛的一个框架 —— Spring Boot&#xff0c;我们会循序渐进地介绍 Spring Boot 的方方面面&#xff0c;包括理论和实战&#xff0c;也会介绍和Spring Boot一些热点面试题。 概论 本文是…

基于Rflysim平台的无人机拦截三维比例导引算法仿真

【后厂村路钢铁侠出品】 一、Rflysim简介 RflySim是一套专为科研和教育打造的Pixhawk /PX4 和MATLAB/Simulink生态系统或工具链&#xff0c;采用基于模型设计&#xff08;Model-Based Design&#xff0c; MBD&#xff09;的思想&#xff0c;可用于无人系统的控制和安全测试。…

社交革命:Facebook如何改变我们的生活

引言 在数字化时代的浪潮中&#xff0c;社交媒体平台成为了人们日常生活不可或缺的一部分&#xff0c;而Facebook作为其中的巨头&#xff0c;已经深刻地改变了我们的生活方式和社交模式。本文将探讨Facebook在社交领域的影响力&#xff0c;以及它是如何改变了我们的生活。 1. …

SQLite数据库浏览器sqlite-web

什么是 sqlite-web &#xff1f; sqlite-web是一个用 Python 编写的基于 Web 的 SQLite 数据库浏览器。 软件特点&#xff1a; 可与您现有的 SQLite 数据库配合使用&#xff0c;也可用于创建新数据库。添加或删除&#xff1a; 表格列&#xff08;支持旧版本的 SQLite&#xff…

春秋云境CVE-2023-1313

简介 cockpit在2.4.1版本之前存在任意文件上传漏洞PS&#xff1a;通过在浏览器中打开/install来运行安装 正文 来到靶场&#xff0c;首先进行弱口令爆破&#xff0c;发现没用&#xff0c;那么只好老老实实的看靶场提示 先来访问/install 访问后就可以进行登录了&#xff0c…

阿里云实时计算Flink的产品化思考与实践【上】

摘要&#xff1a;本文整理自阿里云高级产品专家黄鹏程和阿里云技术专家陈婧敏在 FFA 2023 平台建设专场中的分享。内容主要为以下五部分&#xff1a; 阿里云实时计算 Flink 简介产品化思考产品化实践SQL 产品化思考及实践展望 该主题由黄鹏程和陈婧敏共同完成&#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.…

云原生(六)、CICD - Jenkins快速入门

Jenkuns快速入门 一、CICD概述 CICD是持续集成&#xff08;Continuous Integration&#xff09;和持续部署&#xff08;Continuous Deployment&#xff09;的缩写。它是软件开发中的一种流程和方法论&#xff0c;旨在通过自动化的方式频繁地将代码集成到共享存储库中&#xf…

面试题 之 webpack

1.说说你对webpack理解&#xff1f;解决什么问题&#xff1f; Webpack 是实现前端项目的模块化&#xff0c;用于现代 JavaScript 应用程序的静态模块打包工具&#xff0c;被webpack 直接引用的资源打包进 bunde.js的资源&#xff0c;当webpack 处理应用程序时,它会在内部构建一…

将jupyter notebook文件导出为pdf(简单有效)

1.打开jupyter notebook笔记&#xff1a; 2.点击file->print Preview 3.在新打开的页面右键打印 4.另存为PDF 5.保存即可 6.pdf效果 &#xff08;可能有少部分图片显示不了&#xff09; 网上也有其他方法&#xff0c;比如将其转换为.tex再转为PDF等&#xff0c;但个人觉…

Maplesoft Maple 2024数学软件中文安装 Maple2024 Mac下载

Maplesoft Maple for Mac 是一款功能强大、易于使用的数学计算软件&#xff0c;适用于各种科学计算场景。无论是教学、科研还是工程设计&#xff0c;它都能为用户提供有力的支持。 Maple2024 Mac中文破解补丁 Windows版&#xff1a;点此下载 Maple 2024 mac破解教程 打开镜像…

学习可视化比较好用的网站Apache ECharts

Apache ECharts 是一个基于 JavaScript 的开源可视化图表库&#xff0c;它提供了直观、交互丰富且可高度个性化定制的数据可视化图表。这个库最初由百度团队开源&#xff0c;并在 2018 年初捐赠给了 Apache 基金会&#xff0c;成为 ASF 的孵化级项目。在 2021 年 1 月 26 日&am…

Java常见限流用法介绍和实现

目录 一、现象 ​编辑 二、工具 ​​​​​​1、AtomicInteger,AtomicLong 原子类操作 ​​​​​​2、RedisLua ​​​​​​3、Google Guava的RateLimiter 1&#xff09; 使用 2&#xff09; Demo 3&#xff09; 优化demo 4、阿里开源的Sentinel 三、算法 1、计数…

光伏百科|分布式光伏电站如何开展运维管理工作?

随着经济的不断发展和生活水平的日益提高&#xff0c;节能环保已经成为全社会的责任和共识&#xff0c;分布式光伏电站作为清洁能源走进了千家万户。然而&#xff0c;在分布式光伏电站运行期间&#xff0c;面临监管困难、系统繁多、火灾隐患和运维不当等困难&#xff0c;该如何…

gopher伪协议

基础知识 基本格式 基本格式&#xff1a;URL:gopher://<host>:<port>/<gopher-path>web也需要加端口号80gophert协议默认端口为70gopheri请求不转发第一个字符 get请求 问号&#xff08;&#xff1f;)需要转码为URL编码&#xff0c;也就是%3f回车换行要变…

Patchwork包使用教程,R语言快速组合拼接图片

R语言如何拼接多幅图片&#xff1f; 今天分享的笔记带你领略R语言Patchwork包独特的魅力&#xff0c;patchwork是一个非常流行的用于拼接 ggplot2 图形的包&#xff0c;以一种简单的方式对图形进行排列和组合&#xff0c;不论多复杂的组合图形&#xff0c;都能确保图形之间正确…

社交革命:Facebook如何塑造数字社交的未来

引言 在当今数字化时代&#xff0c;社交媒体已成为人们生活的核心&#xff0c;而Facebook作为其中的领军者&#xff0c;一直在塑造着数字社交的未来。本文将深入探讨Facebook在数字社交领域的地位、影响力以及对未来社交的塑造作用&#xff0c;为读者揭示这场社交革命如何由Fa…