|
| 1 | +import { readFileSync, readdirSync } from 'fs' |
| 2 | +const svgTitle = /<svg([^>+].*?)>/ |
| 3 | +const clearHeightWidth = /(width|height)="([^>+].*?)"/g |
| 4 | +const hasViewBox = /(viewBox="[^>+].*?")/g |
| 5 | +const clearReturn = /(\r)|(\n)/g |
| 6 | +function findSvgFile(dir) { |
| 7 | + const svgRes = [] |
| 8 | + const dirents = readdirSync(dir, { |
| 9 | + withFileTypes: true |
| 10 | + }) |
| 11 | + for (const dirent of dirents) { |
| 12 | + if (dirent.isDirectory()) { |
| 13 | + svgRes.push(...findSvgFile(dir + dirent.name + '/')) |
| 14 | + } else { |
| 15 | + const svg = readFileSync(dir + dirent.name) |
| 16 | + .toString() |
| 17 | + .replace(clearReturn, '') |
| 18 | + .replace(svgTitle, ($1, $2) => { |
| 19 | + // console.log(++i) |
| 20 | + // console.log(dirent.name) |
| 21 | + let width = 0 |
| 22 | + let height = 0 |
| 23 | + let content = $2.replace(clearHeightWidth, (s1, s2, s3) => { |
| 24 | + if (s2 === 'width') { |
| 25 | + width = s3 |
| 26 | + } else if (s2 === 'height') { |
| 27 | + height = s3 |
| 28 | + } |
| 29 | + return '' |
| 30 | + }) |
| 31 | + if (!hasViewBox.test($2)) { |
| 32 | + content += `viewBox="0 0 ${width} ${height}"` |
| 33 | + } |
| 34 | + return `<symbol id="${dirent.name.replace('.svg', '')}" ${content}>` |
| 35 | + }) |
| 36 | + .replace('</svg>', '</symbol>') |
| 37 | + svgRes.push(svg) |
| 38 | + } |
| 39 | + } |
| 40 | + return svgRes |
| 41 | +} |
| 42 | +export const svgBuilder = (path) => { |
| 43 | + if (path === '') return |
| 44 | + const res = findSvgFile(path) |
| 45 | + // console.log(res.length) |
| 46 | + // const res = [] |
| 47 | + return { |
| 48 | + name: 'svg-transform', |
| 49 | + transformIndexHtml(html) { |
| 50 | + return html.replace( |
| 51 | + '<body>', |
| 52 | + ` |
| 53 | + <body> |
| 54 | + <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0"> |
| 55 | + ${res.join('')} |
| 56 | + </svg> |
| 57 | + ` |
| 58 | + ) |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments