/
build-svgs.js
90 lines (68 loc) · 2.3 KB
/
build-svgs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env node
'use strict'
const fs = require('fs').promises
const path = require('path')
const chalk = require('chalk')
const cheerio = require('cheerio')
const SVGO = require('svgo')
const yaml = require('js-yaml')
const iconsDir = path.join(__dirname, '../icons/')
const svgAttributes = {
class: '',
fill: 'currentColor',
xmlns: 'http://www.w3.org/2000/svg'
}
const getSvgoConfig = async () => {
try {
let svgoConfig = await fs.readFile(path.join(__dirname, '../svgo.yml'), 'utf8')
svgoConfig = await yaml.safeLoad(svgoConfig)
return svgoConfig
} catch (error) {
console.error('Couldn\'t read SVGO\'s config!')
console.error(error)
process.exit(1)
}
}
const processFile = (file, config) => new Promise((resolve, reject) => {
file = path.join(iconsDir, file)
fs.readFile(file, 'utf8')
.then(data => {
const svgo = new SVGO(config)
svgo.optimize(data)
.then(result => {
const $ = cheerio.load(result.data)
const svg = $('svg')
svg.replaceWith(() => $('<svg>').append($(this).html()))
for (const [attr, val] of Object.entries(svgAttributes)) {
$(svg).removeAttr(attr)
$(svg).attr(attr, val)
}
const dimensions = $(svg).attr('viewBox').split(' ')
const svgWidth = dimensions[2] / 16
const svgHeight = dimensions[3] / 16
$(svg).attr('width', `${svgWidth}em`)
$(svg).attr('height', `${svgHeight}em`)
$(svg).attr('class', `bi bi-${path.basename(file, '.svg')}`)
fs.writeFile(file, $(svg), 'utf8')
.then(() => {
console.log(`- ${path.basename(file, '.svg')}`)
resolve()
})
.catch(error => reject(error))
})
.catch(error => reject(error))
})
.catch(error => reject(error))
})
const main = async () => {
const basename = path.basename(__filename)
const timeLabel = chalk.cyan(`[${basename}] finished`)
console.log(chalk.cyan(`[${basename}] started`))
console.time(timeLabel)
const files = await fs.readdir(iconsDir)
const config = await getSvgoConfig()
await Promise.all(files.map(file => processFile(file, config)))
console.log(chalk.green(`\nSuccess, ${files.length} icons prepped!`))
console.timeEnd(timeLabel)
}
main()