当前位置:网站首页>Which vite plug-ins can quickly provide development efficiency
Which vite plug-ins can quickly provide development efficiency
2022-07-18 17:38:00 【Young】
1. unplugin-auto-import
vue3 Etc hooks Auto import
Support vue, vue-router, vue-i18n, @vueuse/head, @vueuse/core And so on
effect
// Before introduction
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
// After introduction
const count = ref(0)
const doubled = computed(() => count.value * 2)
install
npm i unplugin-auto-import -D
vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
export default ({ mode }) => defineConfig({
plugins: [
AutoImport({
imports: ['vue', 'vue-router', 'vuex', '@vueuse/head'],
// You can choose auto-import.d.ts The location of the generation , Use ts Recommended setting is 'src/auto-import.d.ts'
dts: 'src/auto-import.d.ts'
}),
]
})
2. unplugin-vue-components
Components are automatically imported on demand .
install :
npm i unplugin-vue-components -D
vite.config.ts
import Components from 'unplugin-vue-components/vite'
// ui Library parser , You can also customize it , Relevant equipment needs to be installed UI library ,unplugin-vue-components/resolvers
// The following centralized parsers are provided , When you use it , You need to install the corresponding UI library , Here we use vant Example
// Note that it contains some other common component libraries , For reference
import {
// ElementPlusResolver,
// AntDesignVueResolver,
VantResolver,
// HeadlessUiResolver,
// ElementUiResolver
} from 'unplugin-vue-components/resolvers'
export default ({ mode }) => defineConfig({
plugins: [
Components({
dirs: ['src/components'], // Destination folder
extensions: ['vue','jsx'], // file type
dts: 'src/components.d.ts', // The output file , It's full of import Component key value pair
// ui Library parser , You can also customize it , Relevant equipment needs to be installed UI library
resolvers: [
VantResolver(),
// ElementPlusResolver(),
// AntDesignVueResolver(),
// HeadlessUiResolver(),
// ElementUiResolver()
],
})
]
})
The original reference to the component needs to be in the target file import Related components , Now you can use it directly without having to be in the target file import 了 , Pay attention to case , Components start with uppercase .
3. vite-plugin-style-import
When you use unplugin-vue-components To introduce ui When I was in the library ,message, notification,toast The imported style will not take effect .
install vite-plugin-style-import, Realization message, notification,toast And so on
install :
npm i vite-plugin-style-import -D
vite.config.ts
import styleImport, {
// AndDesignVueResolve,
VantResolve,
// ElementPlusResolve,
// NutuiResolve,
// AntdResolve
} from 'vite-plugin-style-import'
export default ({ mode }) => defineConfig({
plugins: [
styleImport({
resolves: [
// AndDesignVueResolve(),
VantResolve(),
// ElementPlusResolve(),
// NutuiResolve(),
// AntdResolve()
],
})
]
})
The notes are commonly used UI Component library , Introduce... According to your own needs .
4. vite-plugin-vue-setup-extend
setup Grammatical sugar name enhance , send vue3 Syntax sugar supports name attribute .
vue3 The default syntax is no name Attribute , When we use keep-alive It needs to be used name.
install
npm i vite-plugin-vue-setup-extend -D
vite.config.ts
import { defineConfig} from 'vite'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
export default ({ mode }) => defineConfig({
plugins: [
vueSetupExtend()
]
}
Use
<script setup lang="ts" name="home">
</script>
5. vite-plugin-svg-icons
Used to generate svg Sprite , Easy to use in the project .svg file .
After configuring according to the document , collocation Alibaba vector icon library Use , Just download the good svg Drop the file to the specified directory , Then it can be used happily in the project .
install :
npm i vite-plugin-svg-icons -D
vite.config.ts To configure
import { defineConfig,loadEnv } from 'vite'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons';
const path = require("path");
export default ({ mode }) => defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), 'src/svg')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]'
})
]
})
main.ts add to
import 'virtual:svg-icons-register'
newly build svgIcon.vue
<template>
<svg class="svg-icon" aria-hidden="true">
<use :href="symbolId" />
</svg>
</template>
<script setup lang="ts" name="SvgIcon">
import { computed } from 'vue'
const props = defineProps({
prefix: {
type: String,
default: 'icon'
},
name: {
type: String,
required: true
},
})
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
</script>
<style scope>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.1em; /* because icon The size is set to match the font size , and span The lower edge of the label will align with the baseline of the font , Therefore, it is necessary to set a downward offset scale , To correct visual misalignment */
fill: currentColor; /* Define the color of the element ,currentColor It's a variable , The value of this variable represents the value of the current element color value , If the current element is not set color value , Inherit from the parent element */
overflow: hidden;
}
</style>
In the catalog src Under the new svg Folder , stay Alibaba vector icon library download order.svg Icon , Put in svg In the folder .
Use :
<template>
<div class="home">
<svg-icon name="order" class="icon"></svg-icon>
</div>
</template>
<script setup lang="ts">
// The example uses unplugin-vue-components/vite Plug in automatically introduces custom components
</script>
<style lang="less" scoped>
.icon{
font-size: 200px;
color: #ff0000;
}
</style>
6. vite-plugin-html
One for index.html, Provides compression and based on ejs Template function vite plug-in unit .
By matching .env file , When developing or building a project , Yes index.html Inject dynamic data , For example, replace the website title .
install :
npm i vite-plugin-html -D
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="./favicon.ico" />
<link rel="stylesheet" href="./public/reset.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title><%- title %></title>
</head>
<body>
<div id="app"></div>
<%- injectScript %>
</body>
</html>
vite.config.ts
import { defineConfig,loadEnv} from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default ({ mode }) => defineConfig({
// mode Environment variable name , If configured .env.test, Startup time --mode test, there mode Namely test
plugins: [
createHtmlPlugin({
minify: true,
/**
* Write here entry after , You won't need to be in `index.html` Add in script label , The original label needs to be deleted
* @default src/main.ts
*/
entry: '/src/main.ts',
/**
* Need injection index.html ejs Template data
*/
inject: {
data: {
// lookup .env.test In the document VITE_PROJECT_TITLE, Please use VITE_ ID start
title: loadEnv(mode, process.cwd()).VITE_PROJECT_TITLE,
injectScript: `<script src="/inject.js"></script>`,
},
},
})
]
})
7. vite-plugin-compression
Use gzip perhaps brotli To compress resources .
install
npm i vite-plugin-compression -D
vite.config.ts
import { defineConfig,loadEnv} from 'vite'
import viteCompression from 'vite-plugin-compression';
export default ({ mode }) => defineConfig({
plugins: [
viteCompression()
]
})
8. vite-plugin-imagemin
Pack and compress pictures
install
npm i vite-plugin-imagemin -D
Domestic users need to install on the computer host file (C:\Windows\System32\drivers\etc) Add the following configuration :
199.232.4.133 raw.githubusercontent.com
When I installed it myself, I found it still couldn't work , Then he chose what he didn't recommend cnpm Installation is successful - -
I found my 4M After the picture is compressed , The file was rotated 90 degree , this ?
import { defineConfig,loadEnv} from 'vite'
import viteImagemin from 'vite-plugin-imagemin'
export default ({ mode }) => defineConfig({
plugins: [
viteImagemin({
gifsicle: { // gif Picture compression
optimizationLevel: 3, // choice 1 To 3 Optimization levels between
interlaced: false, // Interlaced scanning gif Progressive rendering
// colors: 2 // Put each output GIF The number of different colors in is reduced to num Or less . The number must be between 2 and 256 Between .
},
optipng: { // png
optimizationLevel: 7, // choice 0 To 7 Optimization levels between
},
mozjpeg: {// jpeg
quality: 20, // The compression quality , Range from 0( The worst ) To 100( The best ).
},
pngquant: {// png
quality: [0.8, 0.9], // Min and max Is between 0( The worst ) To 1( The best ) Number between , Be similar to JPEG. The minimum amount of color required to achieve or exceed the highest quality . If the conversion results in a quality lower than the minimum quality , The image will not be saved .
speed: 4, // Compression speed ,1( strong ) To 11( The fastest )
},
svgo: { // svg Compress
plugins: [
{
name: 'removeViewBox',
},
{
name: 'removeEmptyAttrs',
active: false,
},
],
},
}),
]
})
9. vite-plugin-purge-icons
This plug-in allows us to use it conveniently and efficiently Iconify All icons in ( I said I didn't use …).
10. @vitejs/plugin-vue-jsx
This plug-in supports vue3 Use in jsx/tsx grammar
install
npm i @vitejs/plugin-vue-jsx
vite.config.ts
import { defineConfig,loadEnv} from 'vite'
import vuejsx from "@vitejs/plugin-vue-jsx"
export default ({ mode }) => defineConfig({
plugins: [
vuejsx()
]
})
jsx file :
(jsx Automatically skip lifecycle in components , namely jsx There's no life cycle in it , In the parent component onBeforeMount After execution )
const component = (props:any,context:any) => {
console.log(props)
const onClick = () => {
context.emit('update')
}
return <div
style={
{
fontSize: 12,
color: '#999'
}}
onClick={()=>onClick()}
>
I am a jsx Function component {props.text}
</div>
}
export default component
11. vite-plugin-restart
Modify by listening to the file , Automatic restart vite service .
The most common scenario is listening vite.config.js and .env.development file , We know , modify vite Configuration files and environment configuration files , Yes, it needs to be restarted vite Will take effect , Through this plug-in , We will be free from repeated restart .
install
npm i vite-plugin-restart -D
To configure :vite.config.ts
import ViteRestart from 'vite-plugin-restart'
export default {
plugins: [
ViteRestart({
restart: [
'my.config.[jt]s',
]
})
],
};
12. vitejs-plugin-legacy
Vite The default browser support baseline is native ESM. The plug-in is not native ESM Support for traditional browsers .
13. @vitejs/plugin-vue
vite Support vue Development
14. vite-plugin-vue-images
Automatically import images , The file name of the peer directory cannot be duplicate !
install
npm i vite-plugin-vue-images -D
vite.config.ts
import { defineConfig,loadEnv} from 'vite'
import ViteImages from 'vite-plugin-vue-images'
export default ({ mode }) => defineConfig({
plugins: [
ViteImages({
dirs: ['src/assets'], // The relative path of the image directory
extensions: ['jpg', 'jpeg', 'png', 'svg', 'webp'], // Effective image expansion
customResolvers:[], // Override name -> The default behavior of image path parsing
customSearchRegex: '([a-zA-Z0-9]+)', // Rewrite the method of searching for the variable to be replaced Regex.
}),
]
Suppose there are the following files and paths
logo.png: src/assets/logo.png
name1.jpg: src/assets/test/name1.jpg
Usage mode :
<template>
<div class="home">
<img :src="Logo" />
<img :src="TestName1" />
</div>
</template>
<script setup lang="ts">
</script>
<style lang="less" scoped>
</style>
The plug-in will be converted to :
<template>
<div class="home">
<img :src="Logo" />
<img :src="TestName1" />
</div>
</template>
<script setup lang="ts">
import Logo from '@/assets/logo.png'
import TestName1 from '@/assets/test/name1.jpg'
</script>
<style lang="less" scoped>
</style>
15. vue-global-api
unplugin-auto-import The successor to the plug-in , Solve the problem caused by its automatic import eslint Report errors
install
npm i vue-global-api
main.ts add to
import 'vue-global-api'
边栏推荐
- [actual combat] 1382- Yiwen owns your puppeter crawler application
- V831——AprilTag标签识别
- 【实战】1382- 一文拥有属于你的 puppeteer 爬虫应用
- Alipay sandbox tests mobile website payment, prompting that the merchant's cooperation agreement has expired and cannot continue to be used
- How should both parties bear the large amount of child support after divorce
- 因果学习将开启下一代AI浪潮?九章云极DataCanvas正式发布YLearn因果学习开源项目
- Vim使用学习以及ideaVim(持续补充)
- Analysis of websocket hijacking
- ETCD数据库源码分析——etcdserver bootstrap初始化cluster和raft
- 数据湖基本架构
猜你喜欢

(PC+WAP)织梦模板公司行业通用类网站

V831 - apriltag tag identification

2022年全球職業教育行業發展報告

如何在Kubernetes上搭建code-server 云IDE平台

Flink1.7从安装到体验

Diabetes genetic risk testing challenge -toggle 30 days of ML

W806 development board driver ov2640 reads JPEG pictures 1600x1200 resolution

HCIA-R&S自用笔记(9)数据转发过程、单播/多播/组播

STC8H开发(十四): I2C驱动RX8025T高精度实时时钟芯片

Ericsson asked for prohibition on the grounds of infringement, and apple returned to the United States to counterclaim. This scene is so familiar
随机推荐
Postgresql源码(7)Xlog格式
Rapport mondial sur le développement de l'industrie de l'enseignement professionnel 2022
How to multiply bank revenue through customer value analysis
关于cJSON的valueint超过整型范围的问题
Win11色温如何进行调整设置
How to build a code server cloud ide platform on kubernetes
PCB芯片散热焊盘如何设计?
从物理转 AI 、战数据库,95后程序员的职业选择
Pytest+allure custom report
Etcd database source code analysis -- etcdserver bootstrap initialization cluster and raft
js base64转图片
flutter实现hero图片渐变放大 圖片等比方法圖片平滑放大
Njupt "Xin'an numeral base" Chapter 11 introduction to problem solving
PostgreSQL source code (5) buffer management
HCIA-R&S自用笔记(9)数据转发过程、单播/多播/组播
电脑PC与S7-200SMART PLC不在同一网段,如何建立通信连接?
Image verification, slider verification solution
jetlinks平台Mqtt设备接入认证问题
【踩坑合辑】7.14
文件解析漏洞详解