-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfontawesome.config.js
217 lines (182 loc) · 5.2 KB
/
fontawesome.config.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const { xml2js, js2xml } = require('xml-js');
const CONFIG_FILENAME = 'fa.config.js';
const ERROR_CONFIG_FILE_LOADING = 'Error loading the config file';
const ERROR_OPTIONS_TYPE = 'Error Type Options: expected an object';
const ERROR_WHITELIST_TYPE = 'Error Type option whitelist: expected an object';
const ERROR_MISSING_CONTENT = 'No content provided.';
const ERROR_MISSING_SVGS = 'No svgs provided.';
const defaultOptions = {
svgs: [],
content: [],
whitelist: { '*': new Set() },
};
const removeDuplicates = (filePath, index, array) => array.indexOf(filePath) === index;
const flatten = (arr, initialVal) => [...arr, ...initialVal];
class PurgeSvg {
constructor(options) {
if (typeof options === 'string' || typeof options === 'undefined') {
options = PurgeSvg.loadConfigFile(options);
}
PurgeSvg.validateOptions(options);
this.options = Object.assign(defaultOptions, options);
}
static loadConfigFile(configFile = CONFIG_FILENAME) {
try {
return require(path.resolve(process.cwd(), configFile));
} catch (e) {
throw new Error(ERROR_CONFIG_FILE_LOADING);
}
}
static validateOptions(options) {
if (typeof options !== 'object') {
throw new TypeError(ERROR_OPTIONS_TYPE);
}
if (!options.content || !options.content.length) {
throw new TypeError(ERROR_MISSING_CONTENT);
}
if (!options.svgs || !options.svgs.length) {
throw new TypeError(ERROR_MISSING_SVGS);
}
if (
options.whitelist &&
(typeof options.whitelist !== 'object' || Array.isArray(options.whitelist))
) {
throw new TypeError(ERROR_WHITELIST_TYPE);
}
}
static globPaths(paths) {
if (typeof paths === 'string') {
paths = [paths];
}
return paths
.map(filePath => {
if (fs.existsSync(filePath)) {
return [filePath];
}
return [...glob.sync(filePath, { nodir: true })];
})
.reduce(flatten, [])
.filter(removeDuplicates)
.map(filePath => path.resolve(filePath));
}
static prepareSvgPaths(svgs) {
return svgs
.map(svg => {
if (typeof svg === 'string') {
svg = { in: svg };
}
const paths = fs.existsSync(svg.in) ? [svg.in] : glob.sync(svg.in, { nodir: true });
return paths.map(svgPath => {
let out = svg.out || path.resolve(svgPath).replace('.svg', '.purged.svg');
// check if output is a folder
if (!out.endsWith('.svg')) {
out = path.format({
dir: out,
base: path.basename(svgPath),
});
}
return {
filename: path.basename(svgPath),
in: path.resolve(svgPath),
out,
prefix: svg.prefix || '',
};
});
})
.reduce(flatten, []);
}
static extractContentIds(content) {
const icons = {};
const regex = /['|"]([tlrsdb]-\S*)['|"]/g;
PurgeSvg.globPaths(content).forEach(filePath => {
if (/fa.names.ts/g.test(filePath)) return;
const content = fs.readFileSync(filePath, 'utf-8');
let m;
while ((m = regex.exec(content)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
const svgFile = path.basename(m[1]);
if (!(icons[svgFile] instanceof Set)) {
icons[svgFile] = new Set();
}
icons[svgFile].add(m[2]);
}
});
return icons;
}
purge() {
const contentIds = PurgeSvg.extractContentIds(this.options.content);
const outSvgs = {};
PurgeSvg.prepareSvgPaths(this.options.svgs).forEach(svgObj => {
const ids = new Set([
...Object.keys(contentIds),
...(contentIds[svgObj.filename] || []),
...(this.options.whitelist[svgObj.filename] || []),
...(this.options.whitelist['*'] || []),
]);
const svg = xml2js(fs.readFileSync(svgObj.in, 'utf8'), { compact: true });
let symbols = svg.svg.symbol;
if (typeof symbols === 'undefined') {
symbols = svg.svg.defs.symbol;
}
if (typeof symbols === 'undefined') {
return;
}
if (!Array.isArray(symbols)) {
symbols = [symbols];
}
if (!Array.isArray(outSvgs[svgObj.out])) {
outSvgs[svgObj.out] = [];
}
outSvgs[svgObj.out].push(...symbols.filter(s => ids.has(s._attributes.id)));
});
for (const filename in outSvgs) {
const svg = {
_declaration: {
_attributes: {
version: '1.0',
encoding: 'UTF-8',
},
},
svg: {
_attributes: {
xmlns: 'http://www.w3.org/2000/svg',
style: 'display: none;',
},
symbol: outSvgs[filename],
},
};
const idGenerated = Object.values(svg.svg.symbol).map(s => s._attributes.id);
if (idGenerated.length !== 0)
console.log('fontawesome bundle generated: ', idGenerated);
else console.log('no fontawesome usage found');
if (!fs.existsSync(path.dirname(filename))) {
fs.mkdirSync(path.dirname(filename));
}
fs.writeFileSync(filename, js2xml(svg, { compact: true, spaces: 2 }));
}
}
}
const overrideWebpackConfig = ({ context, webpackConfig, pluginOptions }) => {
console.log('Generating fontawesome bundle ... ');
try {
new PurgeSvg({
content: [`**/*.tsx`, `**/*.ts`],
svgs: [
{
in: './src/Assets/fontawesome/svg/*.fa.svg',
out: './src/Assets/fontawesome/fa.bundle.svg',
},
],
}).purge();
} catch (e) {}
return webpackConfig;
};
module.exports = {
overrideWebpackConfig,
pathSep: path.sep,
};