Skip to content

Commit 752cfaa

Browse files
fix: resolve webpack/Next.js WASM data URL compatibility issue (#95) (#231)
Add Vite plugin to remove unnecessary `import.meta.url` argument from data: URLs during build. ## Problem wasm-pack generates: `new URL("data:...", import.meta.url)` The `import.meta.url` argument is unnecessary for data: URLs and causes: - Webpack 5: "Invalid generator object" error - Vite: Incorrectly rewrites URL as filesystem path ## Solution Transform during build: - Before: `new URL("data:...", import.meta.url)` - After: `new URL("data:...")` This allows Next.js/webpack users to import spark normally without errors. Fixes #95
1 parent 196721e commit 752cfaa

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

vite.config.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,36 @@
11
import fs from "node:fs";
22
import path from "node:path";
3+
import type { Plugin } from "vite";
34
import { defineConfig } from "vite";
45
import dts from "vite-plugin-dts";
56
import glsl from "vite-plugin-glsl";
67

8+
/**
9+
* Vite plugin to fix WASM data URL compatibility with webpack/Next.js.
10+
*
11+
* wasm-pack generates code like: new URL("data:...", import.meta.url)
12+
* The import.meta.url argument is unnecessary for data: URLs and causes
13+
* webpack/Vite to incorrectly try to rewrite the URL as a file path.
14+
*
15+
* This plugin transforms:
16+
* new URL("data:...", import.meta.url) → new URL("data:...")
17+
*
18+
* See: https://github.com/sparkjsdev/spark/issues/95
19+
*/
20+
function fixWasmDataUrl(): Plugin {
21+
return {
22+
name: "fix-wasm-data-url",
23+
renderChunk(code) {
24+
// Match: new URL("data:...", import.meta.url)
25+
// The data URL can contain any characters including quotes (escaped)
26+
const dataUrlPattern =
27+
/new\s+URL\(\s*("data:[^"]*")\s*,\s*import\.meta\.url\s*\)/g;
28+
const result = code.replace(dataUrlPattern, "new URL($1)");
29+
return result !== code ? result : null;
30+
},
31+
};
32+
}
33+
734
const assetsDirectory = "examples/assets";
835
const localAssetsDirectoryExist = fs.existsSync(assetsDirectory);
936
if (!localAssetsDirectoryExist) {
@@ -32,6 +59,9 @@ export default defineConfig(({ mode }) => {
3259
}),
3360

3461
dts({ outDir: "dist/types" }),
62+
63+
// Fix webpack/Next.js compatibility for WASM data URLs
64+
fixWasmDataUrl(),
3565
{
3666
name: "serve-node-modules-alias",
3767
configureServer(server) {

0 commit comments

Comments
 (0)