Vue 3 + TypeScript + Vite 2024年4月最新管理系统基建

Vue 3 + TypeScript + Vite 2024年4月最新管理系统基建

相关依赖

  • vue: ^3.4.21
  • vite: ^5.2.0
  • typescript: ^5.2.2
  • eslint: ^9.0.0

1. 初始化项目

1.1 node版本要求

node: v18.17.1

1.2. 创建项目

使用 PNPM:

# 创建项目
pnpm create vite vue3-element-template --template vue-ts
# 安装依赖
pnpm install
# 启动项目
cd my-vue-app
pnpm run dev
# 构建项目
pnpm run build

2. 配置 tsconfig.json

修改 tsconfig.json, 删除tsconfig.node.json

{
	"compilerOptions": {
		"target": "ES2020", // 将代码编译为ES2020版本的 JS
		"useDefineForClassFields": true, // 将 class 声明中的字段语义从 [[Set]] 变更到 [[Define]]
		"module": "ES2020", // 使用 ES Module 格式打包编译后的文件
		"lib": ["ES2020", "DOM", "DOM.Iterable"], // 使用 Node 的模块解析策略
		"skipLibCheck": true, // 跳过对 .d.ts 文件的类型检查

		/* Bundler mode */
		"moduleResolution": "bundler", // 使用 Node 的模块解析策略 , 一般配合上面的module
		"allowImportingTsExtensions": true, // 允许 TypeScript 文件使用特定于 TypeScript 的扩展名(如 .ts、.mts 或 .tsx)相互导入。
		"resolveJsonModule": true, // 允许引入 JSON 文件
		"isolatedModules": true, // 要求所有文件都是 ES Module 模块。
		"noEmit": true, // 不输出文件,即编译后不会生成任何js文件
		"jsx": "preserve", // 保留原始的 JSX 代码,不进行编译

		/* Linting */
		"strict": true, // 开启所有严格的类型检查
		"noUnusedLocals": true, //报告未使用的局部变量的错误
		"noUnusedParameters": true, //报告函数中未使用参数的错误
		"noFallthroughCasesInSwitch": true, //确保switch语句中的任何非空情况都包含
		"allowJs": true, //允许使用js
		"noImplicitAny": false /* 不允许隐式的any类型 */,
		"forceConsistentCasingInFileNames": true /* 是否强制代码中使用的模块文件名必须和文件系统中的文件名保持大小写一致 */,
		"baseUrl": ".", //查询的基础路径
		"paths": { "@/*": ["src/*"], "#/*": ["types/*"] }, //路径映射,配合别名使用
		"types": [
			// 编译过程中被包含进来的类型声明文件
			"node",
			"vite/client"
		]
	}
}

tsconfig.json 会有Error提示:找不到“node”的类型定义文件。

3. 配置路径别名

3.1 安装Node.js API的ts类型
pnpm add @types/node -D

对应tsconfig.json文件:

  "types": [
    "node",
    "vite/client"
  ]

其中 node 表示 “node”的类型声明文件 @types/node 会被加载进来。

3.2 修改vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path' // 引入path模块

export default defineConfig({
	plugins: [vue()],
	resolve: {
		// 配置别名
		alias: {
			'@': path.resolve('./src'),
			'#': path.resolve('./types'),
		},
	},
})

对应tsconfig.json文件:

"paths": {
  "@/*": ["src/*"],
  "#/*": ["types/*"]
}

如果此时 vite.config.ts 文件的 plugins: [vue()] 有报错,重启VScode可解决。

4. 配置 ESLint 和 prettier

4.1 开发工具配置

本文使用代码编辑器为 VSCode,需安装好了相应的插件 Vue - Official(v2.0.10),ESLint 以及 Prettier。

4.2 ESLint 的初始化
pnpm create @eslint/config
√ How would you like to use ESLint? · problems
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ Does your project use TypeScript? · typescript
√ Where does your code run? · browser
The config that you've selected requires the following dependencies:

eslint, globals, @eslint/js, typescript-eslint, eslint-plugin-vue
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · pnpm

这时候项目根路径下就会生成一份 ESLint 的配置文件 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 [
	{ languageOptions: { globals: globals.browser } },
	pluginJs.configs.recommended,
	...tseslint.configs.recommended,
	...pluginVue.configs['flat/essential'],
]

此时,如果更改VSCode 的配置文件 settings.json

  • 添加如下内容可使用 ESLint 在保存时格式化代码:
	"eslint.experimental.useFlatConfig": true //, 启用 eslint 配置扁平化
	"editor.formatOnSave": true, // 保存时进行格式化
	"editor.defaultFormatter": "dbaeumer.vscode-eslint", // 设置 ESLint 为默认格式化工具
	"eslint.format.enable": true, // 启用 ESLint 格式化下面添加入 validated 的文件
	"eslint.validate": [
		"javascript",
		"javascriptreact",
		"typescript",
		"typescriptreact",
		"vue",
		"html",
		"markdown",
		"json",
		"jsonc",
		"yaml"
	],
4.3 安装 prettier
pnpm install -D eslint-plugin-prettier	eslint-config-prettier

修改 eslint.config.js 添加 prettier 配置

import globals from 'globals'
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'
import pluginPrettierRecommendedConfigs from 'eslint-plugin-prettier/recommended'

export default [
	// eslint 默认推荐规则
	pluginJs.configs.recommended,
	// ts 默认推荐规则
	...tseslint.configs.recommended,
	// vue3 基础推荐规则
	...pluginVue.configs['flat/recommended'],
	// prettier 默认推荐规则
	pluginPrettierRecommendedConfigs,
	{
		languageOptions: { globals: globals.browser },
	},
]

根目录下新建 prettier.config.js:

export default {
	tabWidth: 2,
	useTabs: true,
	semi: false,
	singleQuote: true,
	printWidth: 120,
	arrowParens: 'always',
	bracketSpacing: true,
	endOfLine: 'auto',
	vueIndentScriptAndStyle: true,
}

这个时候保存时,就会使 eslint 按照 prettier 配置的规则进行格式化,如果有其他错误,重启vscode可解决。

4.4 配置 vue 检测

如果此时打开 components/HelloWorld.vue 文件,会发现此行报错:

defineProps<{ msg: string }>() // Parsing error: Unexpected token )eslint

解决办法: 配置 vue-eslint-parser,修改eslint.config.js

import globals from 'globals'
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'
import pluginPrettierRecommendedConfigs from 'eslint-plugin-prettier/recommended'
import parserVue from 'vue-eslint-parser'

export default [
	// eslint 默认推荐规则
	pluginJs.configs.recommended,
	// ts 默认推荐规则
	...tseslint.configs.recommended,
	// vue3 基础推荐规则
	...pluginVue.configs['flat/recommended'],
	// prettier 默认推荐规则
	pluginPrettierRecommendedConfigs,
	{
		languageOptions: {
			globals: {
				...globals.browser,
				...globals.es2020,
				...globals.node,
			},
			ecmaVersion: 2020,
			parser: parserVue,
			parserOptions: {
				parser: tseslint.parser,
			},
		},
	},
	// 可添加一些自定义规则
	rules: {
		'no-unused-vars': ['off', { caughtErrors: 'none' }], // 未使用变量
		'@typescript-eslint/no-unused-vars': ['off', { caughtErrors: 'none' }], // 未使用变量
		'vue/no-unused-vars': ['off', { caughtErrors: 'none' }], // 未使用变量
		'vue/v-on-event-hyphenation': 'off', // html元素上事件函数名使用短横线连接
		'vue/multi-word-component-names': ['off'], // 组件名应该多个词组成
		'vue/require-default-prop': 'warn', // props 参数 应该有默认值
		'vue/no-v-html': 'off', // 不推荐使用 v-html
		'vue/no-mutating-props': 'warn', // props 参数应该不能直接修改
	},
]

至此,保存文件时会按照eslint 和 prettier 的规则进行格式化。

4.4 添加插件 vite-plugin-eslint

安装

pnpm install -D vite-plugin-eslint

修改 vite.config

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import eslintPlugin from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [vue(), eslintPlugin()],
	resolve: {
		// 配置别名
		alias: {
			'@': path.resolve('./src'),
			'#': path.resolve('./types'),
		},
	},
})

添加 vite-plugin-eslint 类型声明

vite-env.d.ts

/// <reference types="vite/client" />

/**
 * 由于 vite-plugin-eslint 库有点落后,导致 vite 高版本不能正确的识别 cjs 模块
 * 所以这里手动定义
 */
declare module 'vite-plugin-eslint' {
	import { Plugin } from 'vite'
	import { ESLint } from 'eslint'

	/** Plugin options, extending from ESlint options */
	interface Options extends ESLint.Options {
		/** Path to ESLint instance that will be used for linting */
		eslintPath?: string
		/** Check all matching files on project startup */
		lintOnStart?: boolean
		/** A single file, or array of files, to include when linting */
		include?: string | string[]
		/** A single file, or array of files, to exclude when linting */
		exclude?: string | string[]
		/** Custom error formatter or the name of a built-in formatter */
		formatter?: string | ESLint.Formatter['format']
		/** The waring found will be printed */
		emitWarning?: boolean
		/** The errors found will be printed */
		emitError?: boolean
		/** Will cause the module build to fail if there are any warnings, based on emitWarning */
		failOnWarning?: boolean
		/** Will cause the module build to fail if there are any errors, based on emitError */
		failOnError?: boolean
	}

	const content: (rawOptions?: Options) => Plugin
	export default content
}

5. 添加 element-plus 组件库

5.1 按需导入组件

安装unplugin-vue-components 和 unplugin-auto-import这两款插件

pnpm install element-plus
pnpm install -D unplugin-vue-components unplugin-auto-import

把下列代码插入到 vite.config.ts 配置文件中

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
	// ...
	plugins: [
		// ...
		AutoImport({
			imports: ['vue'],
			resolvers: [ElementPlusResolver()],
		}),
		Components({
			resolvers: [ElementPlusResolver()],
		}),
	],
})

配置完后使用vue的api和elementPlus的组件时候会自动导入组件以及类型声明。

并且在根目录生成两个文件:auto-imports.d.ts components.d.ts

还需配置tsconfig.json

{
	...
	"include": ["src/**/*", "auto-imports.d.ts", "components.d.ts"]
}
5.2 国际化

因为Element Plus 组件 默认 使用英语,所以需要设置成中文

ConfigProvider:

<template>
	<el-config-provider :locale="zhCn" size="large">
		<app />
	</el-config-provider>
</template>

<script lang="ts" setup>
	import { defineComponent } from 'vue'
	import { ElConfigProvider } from 'element-plus'
	import zhCn from 'element-plus/es/locale/lang/zh-cn'
</script>

6. 添加 UnoCSS 和 icons 图标

安装插件:

pnpm install -D unocss  @unocss/preset-rem-to-px @iconify/utils @iconify-json/ep
// vite.config.ts
import UnoCSS from 'unocss/vite'

export default defineConfig({
	plugins: [
		...
		UnoCSS()
		...
	],
})

创建 uno.config.ts 文件:

// uno.config.ts
import { defineConfig, presetUno, presetAttributify, presetIcons } from 'unocss'
import presetRemToPx from '@unocss/preset-rem-to-px'
import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'

export default defineConfig({
	presets: [
		presetUno(), // 默认样式预设, 此预设继承了 @unocss/preset-wind 和 @unocss/preset-mini
		presetAttributify(), // 为其他预设和规则提供归因模式。 标签class类名可写为属性
		presetRemToPx({
			// 将 rem 转为 px , 1rem = n px
			baseFontSize: 4, // 默认为 16
		}),
		presetIcons({
			collections: {
				ep: () => import('@iconify-json/ep/icons.json').then((i) => i.default),
				custom: FileSystemIconLoader('./src/assets/', (svg) => svg.replace(/#FFF/, 'currentColor')),
			},
			warn: true,
		}),
	],
})

virtual:uno.css 添加到你的主入口中:

// main.ts
import 'virtual:uno.css'

使用示例:

<div text-9xl text-red inline-block i-custom-vue />
<div text-9xl text-black inline-block i-ep-edit />
6.1 浏览器样式重置
pnpm add @unocss/reset
// main.ts
import '@unocss/reset/normalize.css'

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

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

相关文章

Taro +vue3 中实现全局颜色css变量的设置和使用

当我们现在需要弄一个随时修改的页面颜色主题色 我们可以随时修改 我使用的是 Taro 框架 一般有一个app.less 文件 我们在这个里面 设置一个root 全局样式 :root {--primary-color: #028fd4;--secondary-color: #028fd6;/* 添加其他颜色变量 */ } 这样在全局我们就可以使用这…

uniapp 微信小程序 分享海报的实现

主页面 <template><view class"page"><!-- 自定义导航栏--><Navbar title"我的海报"></Navbar><view class"container"><poster ref"poster" :imageUrl"image" :imageWidth"7…

python之List列表

1. 高级数据类型 Python中的数据类型可以分为&#xff1a;数字型&#xff08;基本数据类型&#xff09;和非数字型&#xff08;高级数据类型&#xff09; 数字型包含&#xff1a;整型int、浮点型float、布尔型bool、复数型complex 非数字型包含&#xff1a;字符串str、列表l…

探索和构建 LLaMA 3 架构:深入探讨组件、编码和推理技术(四)分组多查询注意力

探索和构建 LLaMA 3 架构&#xff1a;深入探讨组件、编码和推理技术&#xff08;四&#xff09;分组多查询注意力 Grouped-query Attention&#xff0c;简称GQA 分组查询注意力&#xff08;Grouped-query Attention&#xff0c;简称GQA&#xff09;是多查询和多头注意力的插值…

【35分钟掌握金融风控策略10】风控策略部署2

目录 策略部署 决策引擎系统简介 基于决策引擎进行策略部署 策略部署结果验证 知识点补充 测试验证 回溯比对 策略部署 策略主要部署在决策引擎上进行风险决策&#xff0c;接下来分别介绍决策引擎系统&#xff0c;以及基于决策引擎进行策略部署的相关内容。 决策引擎系…

java-Spring-(MyBatis框架-xml管理)

目录 前置条件 xml与注解比较 1.1 xml定义 1.2 和SQL注解比较 建包准备 插入数据 ​编辑 更新数据 删除数据 查询数据 查看单字段查询 &#x1f3f7;&#x1f4a3;前置条件 创建一个spring boot 初始化的项目 &#x1f3f7;&#x1f4a3;xml与注解比较 1.1 xml定义 …

微信小程序简单实现购物车功能

微信小程序简单实现购物车结算和购物车列表展示功能 实现在微信小程序中对每一个购物车界面的商品订单&#xff0c;进行勾选结算和取消结算的功能&#xff0c;相关界面截图如下&#xff1a; 具体实现示例代码为&#xff1a; 1、js代码&#xff1a; Page({/*** 页面的初始数…

SpringCloudAlibaba:2.1nacos

概述 概述 简介 Nacos是阿里巴巴开源的服务注册中心以及配置中心 Nacos注册中心Eureka 服务配置Config 服务总线Bus 官网 Nacos官网 | Nacos 官方社区 | Nacos 下载 | Nacos 名字由来 Naming&#xff1a;名字 Configurations&#xff1a;配置 Service&#xff1a;服务 功能…

【基础篇】Git 基础命令与核心概念

✅作者简介&#xff1a;大家好&#xff0c;我是小杨 &#x1f4c3;个人主页&#xff1a;「小杨」的csdn博客 &#x1f433;希望大家多多支持&#x1f970;一起进步呀&#xff01; 一&#xff0c;Git 初识 1.1&#xff0c;问题引入 不知道你工作或学习时&#xff0c;有没有遇到…

Centos8操作系统安装mysql5.7版本以及报错解决

目录 一、卸载MySql 1.首先查看已安装的mysql 2.逐个或者执行一下命令统一卸载掉 注意&#xff1a; 3. 卸载其他相关文件 二、安装MySql 1.安装mysql的rpm源 2.安装MySql 如果遇到以下错误&#xff1a; 问题一: 解决方法&#xff1a; 问题二、 解决方法&#xff1…

国产麒麟v10系统下打包electron+vue程序,报错unknown output format set

报错如下&#xff1a; 报错第一时间想到可能是代码配置原因报错&#xff0c;查看代码似乎感觉没啥问题 又查看具体报错原因可能是因为icon的原因报错&#xff0c;后面查阅发现ico在各系统平台会不兼容&#xff0c;也就是ico是给win下使用的&#xff0c;此处改下图标格式就ok&am…

1、Qt简介

文章目录 前言一、pySide2 / pySide6 ,PyQt5 / PyQt6二、安装包1 安装pyside22 安装pyqt5三、从一个简单的例子开始三、界面动作处理---信号(signal)与槽(slot)(Qt最核心的机制)--- 绑定事件封装到类中总结前言 参考文章:Qt简介 本文开始就开始进入到qt的开发笔记书写…

【论文解读】QUEST: Query Stream for Practical Cooperative Perception

QUEST 摘要引言QUERY COOPERATION PARADIGMQUEST FRAMEWORKA. Overall ArchitectureB. Cross-agent Query Interaction 实验结论 摘要 合作感知通过提供额外的视点和扩展感知领域&#xff0c;可以有效地提高个体感知性能。现有的合作模式要么是可解释的(结果合作)&#xff0c;…

计算机视觉——OpenCV 使用分水岭算法进行图像分割

分水岭算法 分水岭算法&#xff1a;模拟地理形态的图像分割 分水岭算法通过模拟自然地形来实现图像中物体的分类。在这一过程中&#xff0c;每个像素的灰度值被视作其高度&#xff0c;灰度值较高的像素形成山脊&#xff0c;即分水岭&#xff0c;而二值化阈值则相当于水平面&am…

LabVIEW高效目标跟踪系统

LabVIEW高效目标跟踪系统 随着机器视觉技术的飞速发展&#xff0c;设计和实现高效的目标跟踪系统成为了众多领域关注的焦点。基于LabVIEW平台&#xff0c;结合NI Vision机器视觉库&#xff0c;开发了一种既高效又灵活的目标跟踪系统。通过面向对象编程方法和队列消息处理器程序…

以更多架构核心专利,推进 SDS 产业创新创造

今天是第 24 个世界知识产权日&#xff0c;今年世界知识产权日活动的主题是&#xff1a;“知识产权和可持续发展目标&#xff1a;立足创新创造&#xff0c;构建共同未来。” 这也正是 XSKY 在软件定义存储领域的目标之一。以“数据常青”为使命的 XSKY&#xff0c;始终立足于软…

济宁市中考报名照片要求及手机拍照采集证件照方法

随着中考报名季的到来&#xff0c;并且进入了中考报名演练阶段&#xff0c;济宁市的广大考生和家长都开始忙碌起来。报名过程中&#xff0c;上传一张符合要求的证件照是必不可少的环节。本文将详细介绍济宁市中考报名照片的具体要求&#xff0c;并提供一些实用的手机拍照采集证…

LeetCode in Python 74/240. Search a 2D Matrix I/II (搜索二维矩阵I/II)

搜索二维矩阵I其实可以转换为搜索一维数组&#xff0c;原因在于&#xff0c;只要先确定搜索的整数应该在哪一行&#xff0c;即可对该行进行二分查找。 搜索二维矩阵II中矩阵元素排列方式与I不同&#xff0c;但思想大致相同。 目录 LeetCode in Python 74. LeetCode in Pyth…

html表格导出为word文档,导出的部分表格内无法填写文字

导出技术实现&#xff1a;fileSaver.jshtml-docx-js 1.npm安装 npm install --save html-docx-js npm install --save file-saver 2.页面引入 import htmlDocx from html-docx-js/dist/html-docx; import saveAs from file-saver;components: {htmlDocx,saverFile, }, 3.页…

(MSFT.O)微软2024财年Q3营收619亿美元

在科技的浩渺宇宙中&#xff0c;一颗璀璨星辰再度闪耀其光芒——(MSFT.O)微软公司于2024财政年度第三季展现出惊人的财务表现&#xff0c;实现总营业收入达到令人咋舌的6190亿美元。这一辉煌成就不仅突显了微软作为全球技术领导者之一的地位&#xff0c;更引发了业界内外对这家…
最新文章