Created
May 28, 2019 10:01
-
-
Save mknospe/e3adef87e4db20acd3d8ef6502089db5 to your computer and use it in GitHub Desktop.
Synchronous NodeJS script to parse CSS files and read out used font-family, font-weight and font-styles to generate a <link> tag for Google custom fonts.
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 fs = require('fs'); | |
// TODO LIST OF CUSTOM FONTS - ADD NEW FONTS TO IT IF NEEDED | |
const CUSTOM_FONTS_SPECS = [ | |
{ | |
name: 'Open Sans', | |
weights: ['300','300i','400','400i','600','600i','700','700i','800','800i'], | |
defaultWeight: '400', | |
}, | |
{ | |
name: 'Lora', | |
weights: ['400','400i','700','700i'], | |
defaultWeight: '400', | |
}, | |
{ | |
name: 'Nanum Gothic', | |
weights: ['400','700','800'], | |
defaultWeight: '400', | |
}, | |
]; | |
const removeEmpty = item => item; | |
const arrayUnique = (array) => array ? [...new Set(array)] : []; | |
const createFontLink = (fonts) => `<link href="https://fonts.googleapis.com/css?family=${fonts}&display=swap" rel="stylesheet">`; | |
const getValidatedFontStyles = (font, fontStyles) => { | |
const validFont = CUSTOM_FONTS_SPECS.filter(item => item.name === font).pop() || []; | |
const validFontStyles = fontStyles.filter(style => validFont.weights.indexOf(style) !== -1); | |
return (validFontStyles.length > 0) ? validFontStyles : [validFont.defaultWeight]; | |
}; | |
const getFonts = (fontFamilies = [], fontStyles = []) => { | |
return fontFamilies.map(font => { | |
const validFontStyles = getValidatedFontStyles(font, fontStyles).join(','); | |
return `${font.replace(/ /g, '+')}:${validFontStyles}`; | |
}).join('|'); | |
}; | |
const getPages = (dir) => { | |
// TODO IGNORE SPECIFIC FILES AND FOLDERS | |
const ignoreList = [ | |
'.DS_Store', | |
'error404', | |
'.keep', | |
'global', | |
'manifest.json', | |
'service-worker.js', | |
]; | |
return fs.readdirSync(dir, 'utf-8').filter(file => ignoreList.indexOf(file) === -1); | |
}; | |
const parse = (page, content) => { | |
if (content) { | |
const allowed_custom_fonts = CUSTOM_FONTS_SPECS.reduce((acc, item) => { | |
return acc.concat(item.name); | |
}, []).join('|'); | |
const customFontsRegExp = new RegExp(`(${allowed_custom_fonts})|[^]`, 'g'); | |
// parse "font-family" | |
let fontFamilies = content.match(/font-family:(.*);/gi); | |
fontFamilies = fontFamilies.map(ff => { | |
return ff.replace(customFontsRegExp, '$1'); | |
}) | |
.filter(ff => ff.length > 0); | |
fontFamilies = arrayUnique(fontFamilies); | |
// parse "font-weight" and "font-style" | |
let fontStyles = content.match(/\{([^}]+)\}/gi); | |
fontStyles = fontStyles.map(rule => { | |
let font = rule.match(/font-(weight|style):(.*);/gi); | |
if (font && font.length > 0) { | |
font = font.map(item => { | |
return item | |
.replace('normal', 400) | |
.replace('bold', 700) | |
.replace(/(italic|oblique)|[^0-9]/g, '$1') | |
.replace('oblique', 'italic') | |
.trim(); | |
}) | |
.sort(); | |
// if only italic was found, add the regular font weight | |
if (font.length === 1 && font[0] === 'italic') { | |
font.unshift('400'); | |
} | |
// create italic font identifiers -> 300i, 400i | |
if (font.length > 1) { | |
font = [font.join('').replace('talic', '')]; | |
} | |
return font.join(''); | |
} | |
}) | |
.filter(removeEmpty); | |
fontStyles = arrayUnique(fontStyles); | |
fontStyles.sort(); | |
const fonts = getFonts(fontFamilies, fontStyles); | |
const customFontLink = createFontLink(fonts); | |
if (fonts && customFontLink) { | |
return { | |
page, | |
customFontLink | |
}; | |
} | |
} | |
}; | |
const generateGoogleCustomFontLinksFromCss = (path) => { | |
return getPages(path).map(folderName => { | |
const page = `/${folderName}/index.html`; | |
const file = `${path}/${folderName}/css/style.css`; | |
try { | |
const css = fs.readFileSync(file, 'utf-8'); | |
return parse(page, css); | |
} catch(e) { | |
console.log('> File not found:', file); | |
} | |
}) | |
.filter(removeEmpty) | |
.reduce((obj, item) => Object.assign(obj, {[item.page]: item.customFontLink}), {}); | |
}; | |
module.exports = generateGoogleCustomFontLinksFromCss; | |
// TODO -> pls leave the following lines for debugging | |
// const path = require('path'); | |
// console.log(generateGoogleCustomFontLinksFromCss(path.join(__dirname, '../../../dist'))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment