-
Notifications
You must be signed in to change notification settings - Fork 35
/
fontawesomeToSvg.js
83 lines (74 loc) · 2.14 KB
/
fontawesomeToSvg.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
const { camelCase } = require("lodash");
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
const root = j(fileInfo.source);
// Find all JSX elements with className starting with "fa-"
const icons = root.find(j.JSXElement, {
openingElement: {
name: {
name: "i",
},
attributes: [
{
name: {
name: "className",
},
},
],
},
});
const iconNames = new Set();
// Convert icons to React Font Awesome format
icons.forEach((icon) => {
const classNameAttr = icon.node.openingElement.attributes.find(
(attr) => attr.name.name === "className"
);
const iconClass = classNameAttr.value.value.split(" ");
const iconName = camelCase(iconClass[1]);
const iconType = iconClass[0].replace("fa-", "");
// Replace <i> element with <FontAwesomeIcon> element
j(icon).replaceWith(
j.jsxElement(
j.jsxOpeningElement(j.jsxIdentifier("FontAwesomeIcon"), [
j.jsxAttribute(
j.jsxIdentifier("icon"),
j.jsxExpressionContainer(j.identifier(iconName))
),
]),
j.jsxClosingElement(j.jsxIdentifier("FontAwesomeIcon")),
[]
)
);
if (iconNames.has(iconName)) {
} else {
iconNames.add(iconName);
// Add import statement for icon
root
.get()
.node.program.body.unshift(
j.importDeclaration(
[j.importSpecifier(j.identifier(`${iconName}`))],
j.literal(`@fortawesome/pro-${iconType}-svg-icons`)
)
);
}
});
const fontawesomeImported = root.find(j.ImportDeclaration, {
source: {
value: "@fortawesome/react-fontawesome",
},
});
if (iconNames.size > 0 && !fontawesomeImported.size()) {
console.log(`adding fontawesome import to ${fileInfo.path}"}`);
// Add import statement for FontAwesomeIcon class
root
.get()
.node.program.body.unshift(
j.importDeclaration(
[j.importSpecifier(j.identifier("FontAwesomeIcon"))],
j.literal("@fortawesome/react-fontawesome")
)
);
}
return root.toSource();
};