41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import { plugin, type BunPlugin } from "bun";
|
|
import path from 'path';
|
|
|
|
const fontPlugin: BunPlugin = {
|
|
name: "Font loader",
|
|
async setup(build) {
|
|
build.onLoad({ filter: /\.font\.css$/ }, async (args) => {
|
|
const css = await Bun.file(args.path).text();
|
|
|
|
const match = css.match(/url\(['"]?([^'")]*)['"]?\)/);
|
|
if (match?.[1]) {
|
|
const fontName = match[1];
|
|
const fontPath = path.resolve(path.dirname(args.path), fontName);
|
|
const fontFile = Bun.file(fontPath);
|
|
if (await fontFile.exists()) {
|
|
const buffer = Buffer.from(await fontFile.arrayBuffer());
|
|
const url = `data:;base64,${buffer.toString('base64')}`;
|
|
const updatedCSS = css.replace(fontName, url)
|
|
.replace(/(\n\s*)*/g, '')
|
|
.replace(/;\s*\}/g, '}')
|
|
.replace(/\s*([{:])\s*/g, '$1');
|
|
|
|
return {
|
|
contents: `import { injectStyle } from '__style_helper__';
|
|
injectStyle(${JSON.stringify(updatedCSS)})`,
|
|
loader: 'js',
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
contents: '',
|
|
loader: 'js',
|
|
};
|
|
});
|
|
}
|
|
};
|
|
|
|
plugin(fontPlugin);
|
|
|
|
export default fontPlugin; |