fix: resolve MuPDF wasm correctly in desktop dev

This commit is contained in:
Weilin Cai 2026-04-07 16:03:06 +08:00
parent 0f2635ab7a
commit 1c4eaf3e6d
3 changed files with 47 additions and 3 deletions

View file

@ -1,13 +1,41 @@
import * as mupdf from "mupdf";
import type { PDFDocument } from "mupdf";
const documentMap = new Map<number, mupdf.PDFDocument>();
type MupdfModule = typeof import("mupdf");
type MupdfWasmModuleConfig = {
locateFile?: (path: string) => string;
};
const wasmModuleConfig = ((globalThis as typeof globalThis & {
$libmupdf_wasm_Module?: MupdfWasmModuleConfig;
}).$libmupdf_wasm_Module ??= {});
// In Vite dev, requests for /node_modules/.../mupdf-wasm.wasm can fall back to
// index.html. Pointing MuPDF at Vite's @fs URL keeps worker startup on the
// actual binary during local development without changing packaged builds.
if (import.meta.env.DEV) {
const devWasmUrl = `/@fs/${__MUPDF_WASM_FS_PATH__}`;
wasmModuleConfig.locateFile = (path: string) => {
if (path.endsWith("mupdf-wasm.wasm")) {
return devWasmUrl;
}
return path;
};
}
const mupdf: MupdfModule = await import("mupdf");
const documentMap = new Map<number, PDFDocument>();
let nextDocId = 1;
const methods: Record<string, (...args: any[]) => any> = {};
methods.openDocument = (buffer: ArrayBuffer, magic: string): number => {
const docId = nextDocId++;
const doc = mupdf.Document.openDocument(buffer, magic) as mupdf.PDFDocument;
const doc = mupdf.Document.openDocument(
buffer,
magic,
) as unknown as PDFDocument;
documentMap.set(docId, doc);
return docId;
};

View file

@ -1 +1,3 @@
/// <reference types="vite/client" />
declare const __MUPDF_WASM_FS_PATH__: string;

View file

@ -4,6 +4,15 @@ import topLevelAwait from "vite-plugin-top-level-await";
import path from "node:path";
const host = process.env.TAURI_DEV_HOST;
const mupdfWasmFile = path.resolve(
__dirname,
"..",
"..",
"node_modules",
"mupdf",
"dist",
"mupdf-wasm.wasm",
);
export default defineConfig({
plugins: [react(), topLevelAwait()],
@ -12,6 +21,11 @@ export default defineConfig({
"@": path.resolve(__dirname, "src"),
},
},
define: {
__MUPDF_WASM_FS_PATH__: JSON.stringify(
mupdfWasmFile.replace(/\\/g, "/"),
),
},
worker: {
format: "es",
},