ReferenceError: Cannot access ‘heap’ before initialization

  javascript, rust, wasm-bindgen, webpack

I am trying to use a wasm compiled from rust bundled with webpack. I have this simple js file that I load in my index.html head:

example-project/src/index.js:

document.addEventListener('readystatechange', async () => {
    if (document.readyState !== 'complete') return;

    const rust = await import('@webline/webline-core');
    rust.greet_async(console.log);
});

But I get this error when I navigate to index.html (served with http-serve):

ReferenceError: Cannot access 'heap' before initialization
    at Module.greet_async (webline_core_bg.js:77)
    at eval (index.js:9)

Chrome Dev Tools Sources > index.js

document.addEventListener('readystatechange', () => {
    if (document.readyState !== 'complete') return;

    rust = __webpack_require__ //.. webpack code omitted here, ignore
    rust.then(m => m.greet_async(console.log))
//                   ^^^^^^^^^^^ <- index.js:9 error here
        .catch(console.error);
});

How do I fix this?

Project information:

@webline/webline-core is a local npm package that I added using `npm link "@webline/webline-core". It has a simple rust file that I adapted from the hello-world tutorial:

webline-core/src/lib.rs:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet_async(f: &js_sys::Function) {
    let this = JsValue::null();
    let _ = f.call1(&this, &JsValue::from_str("Hello world"));
}

example-project/webpack.config.js:

var path = require('path');

module.exports = {
    mode: 'development',
    watch: true,
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'index.js'
    },
    experiments: {
        asyncWebAssembly: true
    }
};

example-project/index.html:

<html lang="en">
<head>
    <script src="./dist/index.js"></script> <!-- this is the bundled version of index.js from above -->
</head>
<body>
    <div>Hello there.</div>
</body>
</html>

Source: Ask Javascript Questions

LEAVE A COMMENT