The foregoing

Hello, everyone. Good did not update, is not very want me ~ 😜. There is no reason to delay so long, hahaha, just lazy… Look at the distance from the last article has been the past four months, yi Zhuo ~

Ok, now let’s get straight to business. Today’s talk is about the configuration and use of SVG.

Why do I want to say this? I have been reading vuE3 knowledge recently, incidentally using Vite to build a project, and using TS.

In my own project, I wanted to use some common component libraries simply, but they were useless. Unable to meet specific business needs, he decided to write his own. Then, I decided to use SVG, just then, I realized that I was getting errors everywhere. So I took the time to check it out. Ho, there is a small difference. So there’s this article. Take note.

Here we go

The body of the

The preparatory work

NPM install svG-sprite-loader -d yarn add SVg-sprite-loader -dCopy the code

Components are written

Once the dependencies are installed, start writing a common component to expose. The purpose of this component is unexplained.

// src/components/svgIcon.vue <! <template> < SVG :class="svgClass" v-bind="$attrs" :style="{color: color}"> -- Here's a linkage, <use :xlink:href="iconName" /> </ SVG > </template> <script lang="ts"> import {defineComponent, computed } from "vue"; Export default defineComponent({name: "SvgIcon", props: {// Because this is being called, pass in props Name: {// Customize the SVG name attribute type: String, required: true,}, color: {// Customize SVG color attributes type: String, default: Const iconName = computed(() => '#icon-${props. Name}'); const svgClass = computed(() => { // console.log(props.name, "props.name"); if (props.name) { return `svg-icon icon-${props.name}`; } return "svg-icon"; // SVG tag}); return { iconName, svgClass, }; }}); <style lang=" SCSS ">. SVG -icon {width: 1.6em; Height: 1.6 em. margin-left: 3px; } </style>Copy the code

Specific explanation see notes oh ~ next look to continue the next step.

SVG write

// SRC/ICONS/SVG/This place is where you can write any SVG you want; Eg:Copy the code

The location of these folders, name ah, all depends on personal preference, how to operate, how to operate. Be as happy as you like, but be formal.

Global injection

Injecting the SVG-icon component globally in main.ts is an act of soul injection. Ha ha ha ha

   //main.ts
    import svgIcon from './components/SvgIcon.vue'
    
    app.use(router).use(store, key).use(ElementPlus, { i18n: i18n.global.t, size: globalComponentSize }).use(i18n).use(VueGridLayout).component('svg-icon', svgIcon).mount('#app');
Copy the code

The goal is to mount this component globally.

Plugin in Vite (that’s the point)

If you are using TS, then this is the key, because do not do this step, will not return to effect, various error, please refer to the specific

Click on me for details

That’s one of the mechanics.

All right, let’s get started on this

// src/plugins/Builder.js import { readFileSync, readdirSync } from 'fs' let idPerfix = '' const svgTitle = /<svg([^>+].*?) >/ const clearHeightWidth = /(width|height)="([^>+].*?) "/g const hasViewBox = /(viewBox="[^>+].*?" )/g const clearReturn = /(\r)|(\n)/g function findSvgFile(dir) { const svgRes = [] const dirents = readdirSync(dir, { withFileTypes: true }) for (const dirent of dirents) { if (dirent.isDirectory()) { svgRes.push(... findSvgFile(dir + dirent.name + '/')) } else { const svg = readFileSync(dir + dirent.name) .toString() .replace(clearReturn, '') .replace(svgTitle, ($1, $2) => { // console.log(++i) // console.log(dirent.name) let width = 0 let height = 0 let content = $2.replace( clearHeightWidth, (s1, s2, s3) => { 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 } export const svgBuilder = (path, perfix = 'icon') => { if (path === '') return idPerfix = perfix const res = findSvgFile(path) // console.log(res.length)  // const res = [] return { name: 'svg-transform', transformIndexHtml(html) { 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 the code

Getting into the soul

SRC/ICONS/SVG/import all SVG files from SRC/ICONS/SVG /.

    import { svgBuilder } from './src/plugins/svgBuilder'; 
    plugins: [
        svgBuilder('./src/icons/svg/')
    ],
 
Copy the code

use

Well, when everything is done, you’re ready to use it.

Specific use:

Import SvgIcon from "@/components/ svgicon.vue "; import SvgIcon from "@/components/ svgicon.vue "; // components: { SvgIcon }, // <SvgIcon :name="fail"></SvgIcon>Copy the code

If you want to encapsulate this icon in your other components, it’s easy

conclusion

Ok, so that’s how to use SVG for the VuE3 project built with vite packaging.

We don’t know when the next update will be set, not sure.

I don’t know what to do or where to go these days. In other words, a strong sense of what to do and how to do it. There was a long bottleneck.

Ok, finish reading this article and leave work early ~ wish everyone a happy holiday. High up, bye