reactjs - 如何使用 vfs_fonts.js 减小 bundle.js 文件的大小?
问题描述
我正在使用 react/typescript 开发 pdf 下载功能。(使用 pdfmake)
我的 bundle.js 文件太大了。(超过 8MB)所以,我想减少这个。
主要原因是 bundle.js 包含 vfs_fonts.js。此文件大小超过 17MB。
我试过动态获取字体文件而不是捆绑文件,参考这个页面。
https://github.com/bpampuch/pdfmake/issues/1374
但它没有用。
这是我的代码的一部分
import * as pdfMake from 'pdfmake/build/pdfmake';
function fetchFont (fontURL: string) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', fontURL, true);
request.responseType = 'arraybuffer';
request.onload = function (e: any) {
resolve(request.response);
};
request.onerror = reject;
request.send();
});
}
interface Dictionary {
[index: string]: string;
}
class PdfFontLoader {
fontDefs: Dictionary[];
vfs: {};
loaded: boolean;
constructor () {
this.fontDefs = [];
this.vfs = {};
}
addFont (fontDef: Dictionary) {
this.fontDefs.push(fontDef);
}
load() {
return new Promise((resolve, reject) => {
if (this.loaded) {
resolve();
} else {
const fetches = this.fontDefs.map(fontDef => {
return fetchFont(fontDef.URL).then((data) => {
console.log('fetched ' + JSON.stringify(data));
this.vfs[fontDef.name] = data;
}).catch(e => {
console.log('error ' + e);
});
});
Promise.all(fetches).then(() => {
this.loaded = true;
resolve();
}).catch(reject);
}
});
}
}
const pdf = pdfMake;
pdf.vfs = fontLoader.vfs;
fontLoader.addFont({URL: 'GenShinGothic-Normal.ttf', name: 'GenShinGothic-Normal.ttf'});
fontLoader.addFont({URL: 'GenShinGothic-Bold.ttf', name: 'GenShinGothic-Bold.ttf'});
fontLoader.load().then(res => {
console.log('load finished');
pdf.fonts = {
GenShinGothic: {
normal: 'GenShinGothic-Normal.ttf',
bold: 'GenShinGothic-Bold.ttf'
}
};
console.log("vfs is " + JSON.stringify(pdf.vfs));
控制台日志
load finished
fetched {}
vfs is {"GenShinGothic-Normal.ttf":{},"GenShinGothic-Bold.ttf":{}}
如果生成pdf...
Error: unknown font format
你能帮助我吗?
====附加信息=====字体文件(ttf)与bundle.js部署在同一目录中...
解决方案
推荐阅读
- c++ - Vscode C/C++ 调试器控制台实现
- github-actions - Github Renovate company/package not found composer with auth.json composer
- python-3.x - 使用 Python 请求库进行 Web 抓取,给出 429 客户端错误
- android - 为 kotlin dsl 生成 pom.xml
- javascript - 如何强制用户一一选择选项?
- javascript - 如何输入 createElement DOM 函数的选项?
- ios - 在 mapkit 中选择备用路线的问题
- python - 从 sql 视图获取数据帧的最快方法是什么?
- python - Registering a Prometheus metric in Python ONLY if it doesn't already exist
- java - 如何覆盖android studio中的默认紫色背景颜色