快速开始
- 安装eslint
yarn add eslint -D
- 然后运行初始化eslint
npx eslint --init
- 接着上面命令会自动生成一个新文件eslint.config.js
eslint.config.js
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
export default [
{files: ["**/*.{js,mjs,cjs,ts,vue}"]},
{languageOptions: { globals: globals.browser }},
pluginJs.configs.recommended,
...tseslint.configs.recommended,
...pluginVue.configs["flat/essential"],
{files: ["**/*.vue"], languageOptions: {parserOptions: {parser: tseslint.parser}}},
];
完善后的eslint.config.js 代码:
/*
* @Author: jocongmin 1641626308@qq.com
* @Date: 2024-07-21 15:51:26
* @LastEditors: jocongmin 1641626308@qq.com
* @LastEditTime: 2024-07-21 17:39:24
* @FilePath: \vue3-init\eslint.config.js
* @Description:
*
* Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
*/
import globals from 'globals'
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'
import { readFile } from 'node:fs/promises'
/**
* 由于安装了autoimport 插件,所以,需要引入.eslintrc-auto-import.json 来完善eslint以免不必要的报错
* 如果没有使用autoimport ,就不需要引入了
* @description:
* @return {*}
*/
const autoImportFile = new URL('./.eslintrc-auto-import.json', import.meta.url)
const autoImportGlobals = JSON.parse(await readFile(autoImportFile, 'utf8'))
export default [
{ files: ['**/*.{js,mjs,cjs,ts,vue,tsx}'] },
{
languageOptions: {
globals: {
...globals.browser,
...globals.node,
...autoImportGlobals.globals,
},
},
},
pluginJs.configs.recommended,
...tseslint.configs.recommended,
...pluginVue.configs['flat/essential'],
{
files: ['**/*.vue'],
languageOptions: { parserOptions: { parser: tseslint.parser } },
},
{
rules: {
// eslint(https://eslint.bootcss.com/docs/rules/)
'no-var': 'off', // 要求使用 let 或 const 而不是 var
'no-multiple-empty-lines': ['off', { max: 1 }], // 不允许多个空行
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-unexpected-multiline': 'off', // 禁止空余的多行
'no-useless-escape': 'off', // 禁止不必要的转义字符
'prefer-const': 'off', // 关闭没有使用const的报错
// typeScript (https://typescript-eslint.io/rules)
'@typescript-eslint/no-unused-vars': 'off', // 禁止定义未使用的变量
'@typescript-eslint/no-multiple-empty-lines': 'off', // 禁止定义未使用的变量
'@typescript-eslint/no-var': 'off', // 禁止定义未使用的变量
'@typescript-eslint/prefer-ts-expect-error': 'error', // 禁止使用 @ts-ignore
'@typescript-eslint/prefer-const': 'off', // 关闭没有使用const的报错
'@typescript-eslint/no-explicit-any': 'off', // 禁止使用 any 类型
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-namespace': 'off', // 禁止使用自定义 TypeScript 模块和命名空间。
'@typescript-eslint/semi': 'off',
// eslint-plugin-vue (https://eslint.vuejs.org/rules/)
'vue/multi-word-component-names': 'off', // 要求组件名称始终为 “-” 链接的单词
'vue/script-setup-uses-vars': 'off', // 防止<script setup>使用的变量<template>被标记为未使用
'vue/no-mutating-props': 'off', // 不允许组件 prop的改变
'vue/attribute-hyphenation': 'off', // 对模板中的自定义组件强制执行属性命名样式
},
},
]
.eslintrc-auto-import.json
{
"globals": {
"Component": true,
"ComponentPublicInstance": true,
"ComputedRef": true,
"EffectScope": true,
"ExtractDefaultPropTypes": true,
"ExtractPropTypes": true,
"ExtractPublicPropTypes": true,
"InjectionKey": true,
"PropType": true,
"Ref": true,
"VNode": true,
"WritableComputedRef": true,
"computed": true,
"createApp": true,
"customRef": true,
"defineAsyncComponent": true,
"defineComponent": true,
"effectScope": true,
"getCurrentInstance": true,
"getCurrentScope": true,
"h": true,
"inject": true,
"isProxy": true,
"isReactive": true,
"isReadonly": true,
"isRef": true,
"markRaw": true,
"nextTick": true,
"onActivated": true,
"onBeforeMount": true,
"onBeforeRouteLeave": true,
"onBeforeRouteUpdate": true,
"onBeforeUnmount": true,
"onBeforeUpdate": true,
"onDeactivated": true,
"onErrorCaptured": true,
"onMounted": true,
"onRenderTracked": true,
"onRenderTriggered": true,
"onScopeDispose": true,
"onServerPrefetch": true,
"onUnmounted": true,
"onUpdated": true,
"provide": true,
"reactive": true,
"readonly": true,
"ref": true,
"resolveComponent": true,
"shallowReactive": true,
"shallowReadonly": true,
"shallowRef": true,
"toRaw": true,
"toRef": true,
"toRefs": true,
"toValue": true,
"triggerRef": true,
"unref": true,
"useAttrs": true,
"useCssModule": true,
"useCssVars": true,
"useLink": true,
"useRoute": true,
"useRouter": true,
"useSlots": true,
"watch": true,
"watchEffect": true,
"watchPostEffect": true,
"watchSyncEffect": true,
"IObject": true
}
}
有自己注册的全局方法,也可以写上面.eslintrc-auto-import.json
- package.json 加入eslint命令lint
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint src",
"preview": "vite preview"
},
- yarn run lint 可以控制台查看代码错误问题
总结
上面只是为了实现可以控制台查看eslint的报错提示。
vscode eslint 提示错误实现
需要安装eslint 插件
-
效果
-
安装好eslint后,设置里面开启eslint功能
eslint 开启后会根据eslint.config.js 中的配置进行对应错误提示
vite加入编译eslint错误提示
- 需要安装
yarn add vite-plugin-eslint
- vite.config.js 配置参考
/*
* @Author: jocongmin 1641626308@qq.com
* @Date: 2024-06-02 21:00:27
* @LastEditors: jocongmin 1641626308@qq.com
* @LastEditTime: 2024-07-21 17:30:36
* @FilePath: \vue3-init\vite.config.js
* @Description:
*
* Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
*/
import { fileURLToPath, URL } from 'node:url'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import VueDevTools from 'vite-plugin-vue-devtools'
import eslint from 'vite-plugin-eslint'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
eslint({
// 配置选项
cache: false, // 禁用缓存
}),
AutoImport({
// 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
imports: ['vue', 'vue-router'],
// 生成自动导入的TS声明文件
dts: 'types/auto-import.d.ts', //这个文件会自动生成
eslintrc: {
enabled: false, // Default `false`
filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
},
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [
ElementPlusResolver(),
// 引入 ant-design-vue 图标
IconsResolver({
enabledCollections: ['ep'],
}),
],
dts: false,
}),
// 引入 iconfont
Icons({
autoInstall: true,
}),
VueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})
vscode prettier 配置
-
vscode安装prettier
-
项目中加入 .prettierrc.js文件
.prettierrc.js 配置
/*
* @Author: jocongmin 1641626308@qq.com
* @Date: 2024-07-21 22:42:35
* @LastEditors: jocongmin 1641626308@qq.com
* @LastEditTime: 2024-07-21 23:15:36
* @FilePath: \vue3-init\.prettierrc.js
* @Description:
*
* Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
*/
//此处的规则供参考,其中多半其实都是默认值,可以根据个人习惯改写
export default {
printWidth: 160, // 单行输出(不折行)的(最大)长度
tabWidth: 4, // 每个缩进级别的空格数
tabs: true, // 使用制表符 (tab) 缩进行而不是空格 (space)
semi: true, // 是否在语句末尾打印分号
singleQuote: true, // 是否使用单引号
quoteProps: 'as-needed', // 仅在需要时在对象属性周围添加引号
bracketSpacing: true, // 是否在对象属性添加空格
htmlWhitespaceSensitivity: 'ignore', // 指定 HTML 文件的全局空白区域敏感度, "ignore" - 空格被认为是不敏感的
trailingComma: 'none', // 去除对象最末尾元素跟随的逗号
useTabs: false, // 不使用缩进符,而使用空格
jsxSingleQuote: false, // jsx 不使用单引号,而使用双引号
// arrowParens: 'always', // 箭头函数,只有一个参数的时候,也需要括号
rangeStart: 0, // 每个文件格式化的范围是文件的全部内容
proseWrap: 'always', // 当超出print width(上面有这个参数)时就折行
endOfLine: 'lf', // 换行符使用 lf
'max-lines-per-function': [2, { max: 320, skipComments: true, skipBlankLines: true }] // 每个函数最大行数
}
- vscode setting.json 配置参考
主要还是通过prettier格式化代码
{
// tab 大小为2个空格
"editor.tabSize": 4,
// 100 列后换行
"editor.wordWrapColumn": 100,
// 保存时格式化
"editor.formatOnSave": true,
// 开启 vscode 文件路径导航
"breadcrumbs.enabled": true,
// 显示 markdown 中英文切换时产生的特殊字符
"editor.renderControlCharacters": true,
// eslint 检测文件类型
"eslint.validate": ["vue", "html", "javascript", "typescript", "javascriptreact", "typescriptreact"],
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"eslint.format.enable": true,
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.fontSize": 14,
"[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"workbench.startupEditor": "none",
"diffEditor.ignoreTrimWhitespace": false,
"editor.accessibilitySupport": "off",
"git.openRepositoryInParentFolders": "never",
"eslint.codeAction.showDocumentation": {
"enable": false
},
"eslint.codeActionsOnSave.rules": null
}
-
重启vscode
重启vscode之后,vscode prettier插件就会根据.prettierrc.js文件 的配置进行格式化 -
使用效果
会自动根据配置文件格式化
参考补充
- package.json
{
"name": "vue3-init",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint src",
"fix": "eslint src --fix",
"preview": "vite preview"
},
"dependencies": {
"@types/lodash": "^4.17.5",
"FileSaver": "^0.10.0",
"ailabel": "^5.1.15",
"element-plus": "^2.7.6",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"file-saver": "^2.0.5",
"lodash": "^4.17.21",
"mockjs": "^1.1.0",
"pinia": "^2.1.7",
"prettier": "^3.3.3",
"sass": "^1.77.6",
"typescript": "^5.5.3",
"unplugin-auto-import": "^0.17.6",
"unplugin-element-plus": "^0.8.0",
"unplugin-icons": "^0.19.0",
"unplugin-vue-components": "^0.27.2",
"vite-plugin-eslint": "^1.8.1",
"vue": "^3.4.21",
"vue-router": "^4.3.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@eslint/js": "^9.7.0",
"@iconify-json/ep": "^1.1.15",
"@typescript-eslint/eslint-plugin": "^7.16.1",
"@typescript-eslint/parser": "^7.16.1",
"@vitejs/plugin-vue": "^5.0.4",
"@vitejs/plugin-vue-jsx": "^4.0.0",
"eslint": "9.x",
"eslint-plugin-vue": "^9.27.0",
"globals": "^15.8.0",
"typescript-eslint": "^7.16.1",
"vite": "^5.2.8",
"vite-plugin-vue-devtools": "^7.0.25"
}
}
- "type": "module"
package.json 加入了"type": "module", 的配置,所以所有文件都得import export方式进行导入导出,避免报错
前端工程师、程序员
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~