@bfoese/ngx-preload-fonts
Version:
Angular post-build tool to inject font preload links for fingerprinted fonts into the index file.
65 lines (64 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileUtil = void 0;
const fs = require('fs');
class FileUtil {
static normalizePath(path) {
return path ? path.replace(/\\/g, '/').replace(/\/$/, '') : path;
}
static getFontType(font) {
const fileTypeMatch = font.match(FileUtil.regexFontType);
const fileType = fileTypeMatch && fileTypeMatch.length > 0 ? fileTypeMatch[0].toLowerCase() : undefined;
if (fileType && ['.ttf', '.woff', '.woff2', '.eot', '.otf'].includes(fileType)) {
return fileType.substr(1);
}
return undefined;
}
static containsIndexFile(dir, indexFile) {
return dir && indexFile && fs.existsSync(`${dir}/${indexFile}`);
}
static getAppBuildDirs(root, indexFile) {
const appBuildDirs = [];
if (FileUtil.containsIndexFile(root, indexFile)) {
appBuildDirs.push(root);
}
else {
const children = fs.readdirSync(root);
if (children) {
for (const child of children) {
if (FileUtil.containsIndexFile(`${root}/${child}`, indexFile)) {
appBuildDirs.push(`${root}/${child}`);
}
}
}
}
return appBuildDirs;
}
static getFileName(file) {
const match = file.match(FileUtil.regexFileTypeWithOptionalFingerprint);
return match && match.length > 0 ? file.substr(0, file.indexOf(match[0])) : undefined;
}
static filterFonts(files, include, exclude) {
const fonts = new Map();
if (!files) {
return fonts;
}
for (const file of files) {
const fontType = FileUtil.getFontType(file);
if (!fontType) {
continue;
}
const filename = FileUtil.getFileName(file)?.toLowerCase();
if (exclude && exclude.some((exclude) => filename === exclude.toLowerCase())) {
continue;
}
if (!include || include.some((include) => filename === include.toLowerCase())) {
fonts.set(file, fontType);
}
}
return fonts;
}
}
exports.FileUtil = FileUtil;
FileUtil.regexFontType = /(\.[\w\d]*)$/;
FileUtil.regexFileTypeWithOptionalFingerprint = /((\.[a-z0-9]*)?(\.[\w\d]*){1})$/;