Skip to content

Commit 9d2dfe5

Browse files
committed
make runtime respect options.path
when using cargo-web's built-in backend, the generated standalone runtime hardcoded file path as 'xxx.wasm'. It causes error when the .wasm file is at that location. Thus we use a custom runtime instead to get the .wasm from the correct location.
1 parent a1abb7f commit 9d2dfe5

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

index.js

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ module.exports = function(source) {
4343
const outFile = path.join(outDir, `${packageName}.js`);
4444

4545
const subcmd = `cargo ${builtin ? 'web ' : ''}build`;
46-
const cmd = `${subcmd} --target=${rustTarget}${release ? ' --release' : ''} --verbose`
46+
const cmd = `${subcmd} --target=${rustTarget}${release ? ' --release' : ''} ${builtin ? '--runtime library-es6' : ''} --verbose`
4747

4848
const self = this
4949
child_process.exec(cmd, { cwd: this.context }, function(
@@ -77,22 +77,37 @@ module.exports = function(source) {
7777
fs.readFileSync(wasmFile)
7878
)
7979

80-
if (builtin) {
80+
const wasmPath = path.join(buildPath, `${packageName}.wasm`)
8181

82+
if (builtin) {
8283
// `cargo web build` emits es6 which
8384
// causes problems with `webpack -p`
8485
const es5out = babel.transform(out, {
8586
'presets': ['env']
8687
});
8788

88-
return callback(null, es5out.code);
89-
89+
// use custom runtime because cargo-web standalone runtime currently
90+
// does not support custom file path
91+
// Ref: https://github.com/koute/cargo-web/issues/131
92+
const glue = `
93+
const module = eval(\`${es5out.code}\`);
94+
const { imports } = module();
95+
const wasmPath = '${wasmPath}';
96+
97+
exports.default = () => new Promise((resolve, reject) => {
98+
WebAssembly.instantiateStreaming(fetch(wasmPath), imports).then((obj) => {
99+
resolve(obj.instance.exports);
100+
}, reject);
101+
});
102+
`;
103+
104+
return callback(null, runtime);
90105
}
91106

92107
// This object is passed to the Emscripten 'glue' code
93108
const Module = {
94109
// Path in the built project to the wasm file
95-
wasmBinaryFile: path.join(buildPath, `${packageName}.wasm`),
110+
wasmBinaryFile: wasmPath,
96111
// Indicates that we are NOT running in node, despite 'require' being defined
97112
ENVIRONMENT: 'WEB',
98113
}

0 commit comments

Comments
 (0)