@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
59 lines (57 loc) • 2.22 kB
JavaScript
;
require("core-js/modules/es.string.replace.js");
import path from 'path';
const postcssFontUrlRewrite = function () {
let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
basePath = '/new-path/',
pathPrefixToKeep = 'assets/fonts/',
verbose = false
} = opts;
return {
postcssPlugin: 'font-url-rewrite-plugin',
AtRule: {
'font-face'(atRule) {
atRule.walkDecls('src', decl => {
decl.value = decl.value.replace(/url\(([^)]+)\)/g, (match, rawUrl) => {
const url = rawUrl.replace(/^['"]|['"]$/g, '');
const normalizedUrl = url.replace(/\\/g, '/');
const index = normalizedUrl.lastIndexOf(pathPrefixToKeep);
if (index === -1) {
if (verbose) {
console.warn(`Skipped (no match for "${pathPrefixToKeep}"): ${url}`);
}
return match;
}
const subPath = normalizedUrl.substring(index + pathPrefixToKeep.length);
const filename = path.basename(subPath);
const cleanedFile = filename.replace(/-[a-f0-9]{6,}(?=\.[^.]+$)/, '');
const dir = path.dirname(subPath);
let finalUrl;
if (basePath.startsWith('http://') || basePath.startsWith('https://')) {
const basePathWithoutTrailingSlash = basePath.replace(/\/$/, '');
if (dir === '.') {
finalUrl = `${basePathWithoutTrailingSlash}/${cleanedFile}`;
} else {
const dirWithoutLeadingSlash = dir.replace(/^\//, '');
finalUrl = `${basePathWithoutTrailingSlash}/${dirWithoutLeadingSlash}/${cleanedFile}`;
}
} else {
finalUrl = path.posix.join(basePath, dir, cleanedFile);
}
if (verbose) {
console.log(`
✨ @dnb/eufemia/plugins/postcss-font-url-rewrite
Rewriting: ${url} → ${finalUrl}
`);
}
return `url("${finalUrl}")`;
});
});
}
}
};
};
postcssFontUrlRewrite.postcss = true;
export default postcssFontUrlRewrite;
//# sourceMappingURL=font-url-rewrite-plugin.js.map