Vite创建项目及使用ESLint

238 阅读2分钟

使用 Vite 创建项目

官网地址:cn.vitejs.dev/

创建你的第一个 Vue3 + Typescript 项目

# 请注意 node 版本,至少要在 14 以上
npm create vite@latest

# 按照弹出的提示选择即可

# 通过附加的命令行选项直接指定项目名称和你想要使用的模板
# npm 6.x
npm create vite@latest vue3-basic --template vue-ts

# npm 7+, extra double-dash is needed:
npm create vite@latest vue3-basic -- --template vue-ts

# 模版合集
https://github.com/vitejs/vite/tree/main/packages/create-vite

推荐的插件安装

  1. Vue Language Features (Volar) 能识别vue的代码
  2. TypeScript Vue Plugin (Volar) 能识别vue文件的导入
  3. ESLint

使用ESLint

命令行工具

npm install eslint --save-dev
npx eslint --version

配置文件

# 自动生成配置文件
npm init @eslint/config
# 安装需求进行选择

Rules

ESLint 可用的 Rules

一个 rule 有三个等级 0, 代表关闭,1代表 warning,输出警告,但是不是错误,2 代表错误,会直接抛出错误。这三个数字也可以使用单词来代表,分别是 off warn 和 error。

rules: {
	'semi': 2
}

Extends

一系列的规则作为一组。大家可以把这一组拿来用到自己的项目中,那么这个就是 extends 字段,是一个数组,里面是几个项目,其实在 extends 中的每一个字段,都是一组规则。

# eslint 推荐规则合集
"extends": "eslint:recommended",

eslint.org/docs/latest… 里面有绿色勾的就是启用的设置。

添加 VSCode 设置文件

vscode 默认只会验证 .js 文件,这里我们添加后缀让它验证更多的文件格式。

.vsode/settings.json

{
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "vue",
    "typescript",
    "typescriptreact"
  ]
}

Vite 添加 ESLint 插件

www.npmjs.com/package/vit…

npm install eslint vite-plugin-eslint --save-dev

使用:

import eslint from 'vite-plugin-eslint'

export default defineConfig({
  plugins: [eslint({ cache: false })]
})

简单修改一下 eslintrc 配置文件

清空一下之前测试用的选项,比如 plugins 以及 parser

  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: ['./tsconfig.json']
  },

添加 Vue 官方的ESLint 插件

目前还没发验证 Vue 文件的语法,会直接报错,因为出现了这样的标签。

eslint.vuejs.org/

安装

npm install --save-dev eslint-plugin-vue

修改配置文件

"extends": ["plugin:vue/vue3-essential"],

所有的规则列表:eslint.vuejs.org/rules/

一些规则组:(规则越来越多)

  • plugin:vue/vue3-essential
  • plugin:vue/vue3-strongly-recommended
  • plugin:vue/vue3-recommended
### 添加基于 Typescript  的特殊规则组

目前还没法验证 Typescript 的语法,一些符号会报错,比如泛型的括号。

https://www.npmjs.com/package/@vue/eslint-config-typescript

```bash
npm install @vue/eslint-config-typescript --save-dev

它其实是 typescript-eslint.io/rules/ 一个Vue 的特供版本。

添加对应的 extends

"extends": ["plugin:vue/vue3-essential", '@vue/eslint-config-typescript'],