1. webpack批量导出
核心代码:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
// 通过node的require批量导出
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
2.vite批量导出
深度遍历读取文件夹下的svg文件,然后处理封装成一个数组对象。
利用vite提供的transformIndexHtml钩子函数读取到html源文件,并将svg标签插入到html的body中。
/src/icons/index.js
import {
readFileSync, readdirSync } from 'fs'
// id 前缀
let idPerfix = ''
// 识别svg标签的属性
const svgTitle = /<svg([^>+].*?)>/
// 有一些svg文件的属性会定义height和width,要把它清除掉
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
// 没有viewBox的话就利用height和width来新建一个viewBox
const hasViewBox = /(viewBox="[^>+].*?")/g
// 清除换行符
const clearReturn = /(\r)|(\n)/g
/**
* @param dir 路径
*/
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
}
最后在vite.config.ts中引入
import {
svgBuilder } from './src/icons/index.js'
export default (
mode: 'development' | 'production'
) => {
...
return {
plugins: [svgBuilder('./src/icons/svg/')],
...
}
}