UNPKG

one

Version:

One is a React framework for web, iOS, and Android apps.

79 lines (76 loc) • 2.15 kB
import fs from "node:fs"; import path from "node:path"; import { virtualEntryId } from "./virtualEntryConstants.mjs"; const MIME = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", bmp: "image/bmp", ico: "image/x-icon" }; const ASSET_EXT_RE = /\.(png|jpe?g|gif|webp|avif|bmp|ico)/; function inlineAssetImports(code, id) { if (!ASSET_EXT_RE.test(code)) return null; const importRe = /import\s+(\w+)\s+from\s*['"]([^'"?]+\.(?:png|jpe?g|gif|webp|avif|bmp|ico))['"]\s*;?/g; const base = id.split("?")[0]; let result = code; let changed = false; let m; const edits = []; while (m = importRe.exec(code)) { const [full, name, spec] = m; const abs = spec.startsWith(".") ? path.resolve(path.dirname(base), spec) : null; if (!abs || !fs.existsSync(abs)) continue; const ext = path.extname(abs).slice(1).toLowerCase(); const uri = `data:${MIME[ext] || "application/octet-stream"};base64,${fs.readFileSync(abs).toString("base64")}`; edits.push({ full, name, uri }); } for (const e of edits) { result = result.replace(e.full, `const ${e.name} = ${JSON.stringify(e.uri)};`); changed = true; } return changed ? { code: result, map: null } : null; } function webBundledAssetPlugin() { return { name: "one:web-bundled-asset", transform: (code, id) => inlineAssetImports(code, id) }; } function bundledDevPlugin(enabled) { return { name: "one:bundled-dev", ...enabled ? { transform: { filter: { code: ASSET_EXT_RE }, handler(code, id) { const env = this.environment; if (!env || env.name !== "ssr" || env.mode !== "dev") return; return inlineAssetImports(code, id); } } } : {}, config(_userConfig, env) { if (!enabled || env.command !== "serve") return; return { experimental: { bundledDev: true }, environments: { client: { build: { rolldownOptions: { input: [virtualEntryId], plugins: [webBundledAssetPlugin()], experimental: { lazyBarrel: false }, shimMissingExports: true } } } } }; } }; } export { bundledDevPlugin }; //# sourceMappingURL=bundledDevPlugin.mjs.map