Created
March 21, 2019 00:48
-
-
Save mrukas/ff7893ada7766cfff4a09437f12ee931 to your computer and use it in GitHub Desktop.
Font Awesome Webpack Loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pascalCase = require('pascal-case') | |
const faFolders = [ | |
'@fortawesome/free-solid-svg-icons', | |
'@fortawesome/free-brands-svg-icons', | |
'@fortawesome/free-regular-svg-icons', | |
'@fortawesome/pro-solid-svg-icons', | |
'@fortawesome/pro-regular-svg-icons', | |
'@fortawesome/pro-light-svg-icons' | |
]; | |
function buildIconGraph() { | |
var iconMap = {}; | |
for (var folder of faFolders) { | |
var icons = loadIconPack(folder); | |
if (!icons) { | |
continue; | |
} | |
for (var icon in icons) { | |
iconMap[icon] = folder; | |
} | |
} | |
return iconMap; | |
} | |
function loadIconPack(iconPack) { | |
try { | |
return require(iconPack); | |
} catch (e) { | |
return null; | |
} | |
} | |
const iconMap = buildIconGraph(); | |
module.exports = function loader(source) { | |
var importStatement = | |
"import { library } from '@fortawesome/fontawesome-svg-core'; "; | |
var pattern = /<FontAwesomeIcon.*? icon="(.+?)".*?>/gm; | |
var imports = {}; | |
var addedIcons = {}; | |
while ((matches = pattern.exec(source)) !== null) { | |
var icon = `fa${pascalCase(matches[1])}`; | |
if (addedIcons[icon] !== true) { | |
var path = iconMap[icon]; | |
if (!path) { | |
continue; | |
} | |
var existingPath = imports[path]; | |
if (existingPath) { | |
existingPath.push(icon); | |
} else { | |
imports[path] = [icon]; | |
} | |
addedIcons[icon] = true; | |
} | |
} | |
for (var importPath in imports) { | |
var importLine = `import { ${imports[importPath].join(', ')} } from "${importPath}";`; | |
importStatement += importLine; | |
} | |
for (var importPath in imports) { | |
for (var iconToAdd of imports[importPath]) { | |
importStatement += ` library.add(${iconToAdd});`; | |
} | |
} | |
if (Object.keys(imports).length) { | |
source = `${importStatement} ${source}`; | |
} | |
return source; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment