import { defineConfig, type Plugin } from 'vite' /** * The core library's `requirePeerDep` does `import(moduleName)` where * `moduleName` is a variable — Vite cannot statically analyze that, so the * import fails at runtime in the browser. * * This plugin rewrites the variable import into a lookup of static `import()` * calls that Vite CAN resolve and pre-bundle. */ function resolvePeerDeps(): Plugin { const peerDeps = [ 'pdfjs-dist', 'epubjs', 'docx-preview', 'papaparse', 'highlight.js', 'jszip', 'xlsx', 'node-unrar-js', '@jsquash/jxl', 'utif', ] // Build a code snippet that maps module names → static imports. // highlight.js needs `.default` unwrapping for ESM compatibility. const cases = peerDeps .map((d) => ` case '${d}': return import('${d}').then(m => m.default || m);`) .join('\n') // 7z-wasm's default ESM build imports Node's 'module' built-in, so we // redirect to its UMD build which is browser-safe. const sevenZipCase = ` case '7z-wasm': return import('7z-wasm/7zz.umd.js').then(m => m.default || m);` const replacement = [ '(async (name) => { switch(name) {', cases, sevenZipCase, ' default: throw new Error(`Unknown peer dep: ${name}`);', ' }})(moduleName)', ].join('\n') return { name: 'resolve-polyrender-peer-deps', enforce: 'pre', transform(code: string, id: string) { // Only transform the @polyrender/core bundle if (!id.includes('packages/core')) return if (!code.includes('moduleName')) return // Replace `await import(moduleName)` or `await import(\n moduleName\n)` const result = code.replace( /await\s+import\(\s*(?:\/\*.*?\*\/\s*)?moduleName\s*\)/g, `await ${replacement}`, ) if (result !== code) return result }, } } export default defineConfig({ plugins: [resolvePeerDeps()], // @jsquash/jxl ships a Web Worker whose internal format is "iife". // Forcing workers to ES module format prevents the Rollup error: // "Invalid value 'iife' for option 'worker.format' — UMD and IIFE output // formats are not supported for code-splitting builds." worker: { format: 'es', }, optimizeDeps: { include: [ 'pdfjs-dist', 'epubjs', 'docx-preview', 'papaparse', 'highlight.js', 'jszip', 'xlsx', 'node-unrar-js', '7z-wasm/7zz.umd.js', '@jsquash/jxl', 'utif', ], }, })