A simple solution for vite to batch introduce SVG symbol

Lstmxx 2021-02-23 16:06:59
simple solution vite batch introduce


Preface

Because the company computer is too spicy , Cause every run webpack The waiting time is too slow when I'm waiting ( Sometimes even the window stops working T_T). In order to solve this problem and improve work efficiency , I'm going to take this front-end project from vuecli Migration to vite(2.0) On . But in the process of technical research found that ,svg-sprite-loader There is no support for vite(icon It's all used svg Introduced ), So I can only write one myself vite Of plugin 了 .

principle

If you want to write by yourself , You have to understand svg stay html The use of .

SVG

svg(Scalable Vector Graphics) It's a kind of web Vector graphics language , This means that it will not cause image distortion due to free zooming in and out , More commonly used in icon Exhibition .( Of course , Use svg There are more benefits , For details, see here

stay html Introduce and use svg

stay html Introduction in svg, Generally speaking, the first step is to put more than one svg Convert to multiple symbol And mark it id, Then there will be more symbol Embedded in svg In the label , Finally, it's stuffed in body In the label , The effect is as follows

When you introduce it, you just need to use use The tag introduces the corresponding id Just fine

and svg-sprite-lodaer It is just to help us pass the above manual operation through node.js Batch import .

Realization

After understanding the principle, of course, I started to write .

utilize node.js Bulk read svg file

Use depth traversal to put svg Read out the contents of the document , After processing, save the result in an array .

import { readFileSync, readdirSync } from 'fs'
// id Prefix 
let idPerfix = ''
// distinguish svg Attributes of the tag 
const svgTitle = /<svg([^>+].*?)>/
// Somewhat svg The properties of the file will define height and width, To get rid of it 
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
// No, viewBox If you want to use height and width To create a new viewBox
const hasViewBox = /(viewBox="[^>+].*?")/g
// Clear line breaks 
const clearReturn = /(\r)|(\n)/g
/**
* @param dir route
*/
function findSvgFile(dir: string): string[] {
const svgRes: string[] = []
const dirents = readdirSync(dir, {
withFileTypes: true
})
for (const dirent of dirents) {
const path = dir + dirent.name
if (dirent.isDirectory()) {
svgRes.push(...findSvgFile(path + '/'))
} else {
const svg = readFileSync(path)
.toString()
.replace(clearReturn, '')
.replace(svgTitle, ($1, $2) => {
let width = 0
let height = 0
let content = $2.replace(
clearHeightWidth,
(s1, s2, s3) => {
s3 = s3.replace('px', '')
if (s2 === 'width') {
width = s3
} else if (s2 === 'height') {
height = s3
}
return ''
}
)
if (!hasViewBox.test($2)) {
content += `viewBox="0 0 ${width} ${height}"`
}
return `<symbol id="${idPerfix}-${dirent.name.replace(
'.svg',
''
)}" ${content}>`
})
.replace('</svg>', '</symbol>')
svgRes.push(svg)
}
}
return svgRes
}
 Copy code 

Insert into html Of body in

utilize vite in plugin Provided transformIndexHtml Hook function can read html Source file .

import { Plugin } from 'vite'
···
export const svgBuilder = (path: string, perfix = 'icon'): Plugin => {
if (path === '') return
idPerfix = perfix
const res = findSvgFile(path) // Quote... Above 
return {
name: 'svg-transform',
transformIndexHtml(html): string {
return html.replace(
'<body>',
`
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
${res.join('')}
</svg>
`
)
}
}
}
 Copy code 

Last in vite.config.ts Introduction in .

import type { UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { svgBuilder } from './build/svg/svgBuilder'
export default (
mode: 'development' | 'production'
): UserConfig => {
...
return {
plugins: [vue(), svgBuilder('./src/icons/svg/')],
...
}
}
 Copy code 

Conclusion

Although it's relatively simple , But it's great to help people ( Still can water article ).

github.com/JetBrains/s…

Reference link

版权声明
本文为[Lstmxx]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223155148549E.html

  1. Are airpods still the strongest? Horizontal evaluation of 4 true wireless headphones
  2. Seamless connection with tableau, how can this large bank with 5000 + active users realize self-service analysis?
  3. react-native版文字跑马灯
  4. React native text running lantern
  5. Java、JavaScript、C、C++、PHP、Python都是用来开发什么?
  6. What are Java, JavaScript, C, C + +, PHP and python used to develop?
  7. this.byId(SupplierForm).bindElement in SAP UI5
  8. SAP UI5 JavaScript文件的lazy load - 懒加载
  9. this.byId (SupplierForm).bindElement in SAP UI5
  10. Lazy load lazy load of SAP ui5 JavaScript files
  11. "Gnome 3" - interface elements, desktop components, part names (learning notes) @ 20210223
  12. How to connect the ground gas to the micro front end?
  13. How to transform single / micro service application into serverless application
  14. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  15. Seven array methods for JavaScript you need to master in 2021
  16. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  17. Seven array methods for JavaScript you need to master in 2021
  18. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  19. Seven array methods for JavaScript you need to master in 2021
  20. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  21. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  22. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  23. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  24. 前端面试常考题:JS垃圾回收机制
  25. Frequently asked questions in front end interview: JS garbage collection mechanism
  26. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  27. Java之HTTP网络编程(一):TCP/SSL网页下载
  28. HTTP network programming in Java (1): TCP / SSL web page download
  29. Java之HTTP网络编程(一):TCP/SSL网页下载
  30. HTTP network programming in Java (1): TCP / SSL web page download
  31. 使用vite搭建vue项目
  32. 在组件中展示pdf文件:vue-pdf (由于未找到方法滑动加载下一页,只能点击加载下一页pdf文件)
  33. 在 vue 中通过 express 连接数据库
  34. Using vite to build Vue project
  35. Display PDF file in component: Vue pdf
  36. Connecting database through express in Vue
  37. 2021届秋招哈啰出行前端面经(一面)
  38. vue使用sdk进行七牛云上传
  39. Javascript性能优化【内联缓存】 V8引擎特性
  40. Small true wireless smart headset evaluation: put intelligence into the ear
  41. The front end experience of the 2021 autumn recruitment
  42. Vue uses SDK to upload Qi Niu cloud
  43. 深入理解 Web 协议 (三):HTTP 2
  44. dhtmlxGantt如何重新排序任务
  45. JavaScript performance optimization [inline cache] V8 engine features
  46. 深入理解 Web 协议 (三):HTTP 2
  47. Deep understanding of Web protocol (3): http 2
  48. 深入理解 Web 协议 (三):HTTP 2
  49. How dhtmlxgantt reorders tasks
  50. 深入理解 Web 协议 (三):HTTP 2
  51. JavaScriptBOM操作
  52. JavaScriptBOM操作
  53. Deep understanding of Web protocol (3): http 2
  54. Deep understanding of Web protocol (3): http 2
  55. dhtmlxGantt甘特图重新排序任视频教程
  56. vue实现七牛云上传图片功能
  57. vue.js环境配置步骤及npm run dev报错解决方案
  58. Deep understanding of Web protocol (3): http 2
  59. JavaScript BOM operation
  60. JavaScript BOM operation