Skip to content

Bundlers and Codec Assets

Dus Mamud edited this page Nov 9, 2026 · 1 revision

Bundlers and Codec Assets

Codec packages load their .wasm and glue .js from URLs resolved relative to their own module (new URL('../codec/…', import.meta.url)). Production builds of every major bundler handle this natively. This page covers the one sharp edge — Vite dev — and the override that solves everything else.

Vite dev: pre-bundling breaks the default URLs

In dev, Vite pre-bundles dependencies into node_modules/.vite/deps/, which relocates the codec code; the relative asset URLs then resolve against the wrong place and the WASM request returns the page HTML instead of the binary. Two fixes, both verified against the published packages:

Fix A — exclude the codec packages from pre-bundling

// vite.config.ts
export default defineConfig({
  optimizeDeps: {
    exclude: [
      '@dusrel/image-jpeg', '@dusrel/image-webp', '@dusrel/image-avif',
      '@dusrel/image-png', '@dusrel/image-oxipng', '@dusrel/image-quantize',
      '@dusrel/image-resize', '@dusrel/image-jxl', '@dusrel/image-qoi',
      '@dusrel/image-heic', '@dusrel/image-gif',
    ],
  },
});

(If you change this config, delete node_modules/.vite once so the old pre-bundle is dropped.)

Fix B — hand the loader bundler-emitted URLs

import { setCodecAssets } from '@dusrel/image-jpeg';
import encJs from '@dusrel/image-jpeg/codec/mozjpeg_enc.js?url';
import encWasm from '@dusrel/image-jpeg/codec/mozjpeg_enc.wasm?url';
import decJs from '@dusrel/image-jpeg/codec/mozjpeg_dec.js?url';
import decWasm from '@dusrel/image-jpeg/codec/mozjpeg_dec.wasm?url';

setCodecAssets({
  encodeJsUrl: encJs,
  encodeWasmUrl: encWasm,
  decodeJsUrl: decJs,
  decodeWasmUrl: decWasm,
});

Every codec package exposes the same setCodecAssets. It can be called at any time — if a codec was already used, the new assets take effect on its next load. This is also the mechanism for self-hosting the codec files or pinning them to a CDN.

webpack / Next.js

webpack 5 understands new URL(..., import.meta.url) asset modules natively, so the defaults work. With Next.js, call the processing APIs from client components ('use client') — the codecs are browser-only by definition.

No bundler (CDN / import maps)

Serve the package files as-is and map the package names with an import map — see examples/cdn in the repository, and the live playground, which is built exactly this way.

Hosting checklist

  • Serve .wasm as application/wasm (most static hosts do by default).
  • No COOP/COEP headers needed — all builds are single-threaded.
  • Budget note: the big downloads are the AVIF encoder (~3.4 MB) and the JPEG XL encoder (~2.3 MB). They load lazily, only when the format is actually used, and cache hard — give codec files a long-lived cache header.

Full guide: dusmamud.github.io/dusrel-image/guide/bundlers

Clone this wiki locally