|
| 1 | +// From: https://github.com/ruby-syntax-tree/ruby-syntax-tree.github.io/blob/main/bin/wasmPlugin.js |
| 2 | + |
| 3 | +import path from "node:path"; |
| 4 | +import fs from "node:fs"; |
| 5 | + |
| 6 | +export default { |
| 7 | + name: "wasm", |
| 8 | + setup(build) { |
| 9 | + // Resolve ".wasm" files to a path with a namespace |
| 10 | + build.onResolve({ filter: /\.wasm$/ }, (args) => { |
| 11 | + // If this is the import inside the stub module, import the |
| 12 | + // binary itself. Put the path in the "wasm-binary" namespace |
| 13 | + // to tell our binary load callback to load the binary file. |
| 14 | + if (args.namespace === "wasm-stub") { |
| 15 | + return { |
| 16 | + path: args.path, |
| 17 | + namespace: "wasm-binary", |
| 18 | + }; |
| 19 | + } |
| 20 | + |
| 21 | + // Otherwise, generate the JavaScript stub module for this |
| 22 | + // ".wasm" file. Put it in the "wasm-stub" namespace to tell |
| 23 | + // our stub load callback to fill it with JavaScript. |
| 24 | + // |
| 25 | + // Resolve relative paths to absolute paths here since this |
| 26 | + // resolve callback is given "resolveDir", the directory to |
| 27 | + // resolve imports against. |
| 28 | + if (args.resolveDir === "") { |
| 29 | + return; // Ignore unresolvable paths |
| 30 | + } |
| 31 | + return { |
| 32 | + path: path.isAbsolute(args.path) |
| 33 | + ? args.path |
| 34 | + : path.join(args.resolveDir, args.path), |
| 35 | + namespace: "wasm-stub", |
| 36 | + }; |
| 37 | + }); |
| 38 | + |
| 39 | + // Virtual modules in the "wasm-stub" namespace are filled with |
| 40 | + // the JavaScript code for compiling the WebAssembly binary. The |
| 41 | + // binary itself is imported from a second virtual module. |
| 42 | + build.onLoad({ filter: /.*/, namespace: "wasm-stub" }, async (args) => ({ |
| 43 | + contents: `import wasm from ${JSON.stringify(args.path)} |
| 44 | + export default () => WebAssembly.compile(wasm)`, |
| 45 | + })); |
| 46 | + |
| 47 | + // Virtual modules in the "wasm-binary" namespace contain the |
| 48 | + // actual bytes of the WebAssembly file. This uses esbuild's |
| 49 | + // built-in "binary" loader instead of manually embedding the |
| 50 | + // binary data inside JavaScript code ourselves. |
| 51 | + build.onLoad({ filter: /.*/, namespace: "wasm-binary" }, async (args) => ({ |
| 52 | + contents: await fs.promises.readFile(args.path), |
| 53 | + loader: "binary", |
| 54 | + })); |
| 55 | + }, |
| 56 | +}; |
0 commit comments