Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: wasm functions return undefined #11

Closed
wants to merge 5 commits into from
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 31 additions & 2 deletions src/index.ts
Expand Up @@ -6,6 +6,7 @@ import * as wasmHelper from "./wasm-helper";
export default function wasm(): Plugin {
let resolvedConfig: ResolvedConfig;
let originalWasmPlugin: Plugin;
let moduleIds: string[] = [];

return {
name: "vite-plugin-wasm",
Expand All @@ -20,6 +21,7 @@ export default function wasm(): Plugin {
}
},
async load(id) {
moduleIds.push(id);
if (id === wasmHelper.id) {
return `export default ${wasmHelper.code}`;
}
Expand All @@ -33,14 +35,15 @@ export default function wasm(): Plugin {
// Make a call to Vite's internal `fileToUrl` function by calling Vite's original WASM plugin's load()
const originalLoadResult = (await originalWasmPlugin.load.call(this, id + "?init")) as string;
const url = JSON.parse(/".+"/g.exec(originalLoadResult.trim().split("\n")[1])[0]) as string;
const importUrls = await Promise.all(imports.map(async ({ from }) => getImportUrl(id, from, moduleIds)));

return `
import __vite__initWasm from "${wasmHelper.id}"
${imports
.map(
({ from, names }, i) =>
({ names }, i) =>
`import { ${names.map((name, j) => `${name} as __vite__wasmImport_${i}_${j}`).join(", ")} } from ${JSON.stringify(
from
importUrls[i]
)};`
)
.join("\n")}
Expand All @@ -57,3 +60,29 @@ ${exports
}
};
}

async function getImportUrl(id: string, from: string, moduleIds: string[]) {
const importerPath = id.slice(0, id.lastIndexOf("/")) + from.slice(from.lastIndexOf("/"));
Menci marked this conversation as resolved.
Show resolved Hide resolved
if (importerPath.indexOf("node_modules") === -1) {
// Local js won't have versionHash, so the importerPath is importerId
return importerPath;
}
// The module may be pre-bundled, pre-bundling js file has higher priority than original file.
const preBundlingPath = getPreBundlePath(importerPath);
return (
moduleIds.find(v => v.startsWith(preBundlingPath)) ||
moduleIds.find(v => v.startsWith(importerPath)) ||
importerPath
);
}

function getPreBundlePath(importerPath: string) {
const [prefix, modulePath] = importerPath.split("node_modules/");
const modulePathParts = modulePath.split("/");
let pkgName = modulePathParts[0];
if (pkgName.startsWith("@")) {
// Scope Package
pkgName = `${modulePathParts[0]}_${modulePathParts[1]}`;
}
return `${prefix}node_modules/.vite/deps/${pkgName}.js`;
}