Unable to utilize the web-assembly Rust implementation due to the error stating 'Cannot access '__wbindgen_throw' before initialization'

Looking to integrate some web-assembly into my project, I started off by testing if my webpack setup was functioning properly and able to utilize my .wasm modules. Here's a snippet of what I came up with:

#[wasm_bindgen]
pub fn return_char() -> char {
    return 'a';
}

I then integrated this into the constructor of my web-component (just to confirm everything was running smoothly):

constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = template;
    console.log(return_char());
}

As expected, I saw 'a' in my web-app console:

https://i.sstatic.net/g6Fm1.png

Satisfied with the results, I went on to create a struct with implementation:

#[wasm_bindgen]
pub struct Test {
    value: char
}

#[wasm_bindgen]
impl Test {
    pub fn new() -> Test {
        let value: char = 'a';
        Test {
            value
        }
    }

    pub fn value(&self) -> char {
        self.value
    }

    pub fn change_value(&mut self) {
        self.value = 'b';
    }
}

Next, I instantiated the Test object within the same web-component class constructor and called methods from this implementation. I anticipated seeing both 'a' and 'b' in my console:

constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = template;
    const test: Test = Test.new();
    console.log(test.value());
    test.change_value();
    console.log(test.value());
}

However, things didn't go as planned and I encountered the following error:

Uncaught (in promise) ReferenceError: Cannot access '__wbindgen_throw' before initialization at Module.__wbindgen_throw (calculator_engine_bg.js:5)

I'm unsure why this error is occurring or how to resolve it. Could there be an issue with my webpack.config.js?

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    devtool: 'eval-source-map',
    entry: './src/index.ts',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    experiments: {
        asyncWebAssembly: true
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: 'ts-loader',
                include: [path.resolve(__dirname, 'src')],
            },
        ],
    },
    resolve: {
        extensions: ['.ts', '.js'],
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: path.resolve(__dirname, 'src/index.html'),
            filename: 'index.html',
        }),
    ],
};

GitHub repository containing minimal code for reproduction: webpack-web-assembly-rust-impl-bug

webpack version: 5.0.0-beta.26

Answer №1

Just like sokra pointed out in the response to the issue I raised, it is recommended to utilize experiments.syncWebAssembly instead of experiments.asyncWebAssembly. By implementing this change and using experiments.syncWebAssembly, an additional file needs to be added for asynchronous loading of the index.ts file.

webpack.config.js

module.exports = {
    mode: 'development',
    devtool: 'eval-source-map',
    entry: './src/bootstrap.ts', // !! <- change path to bootstrap.ts
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    experiments: {
        syncWebAssembly: true // !! <- use syncWebAssembly instead of asyncWebAssembly
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: 'ts-loader',
                include: [path.resolve(__dirname, 'src')],
            },
        ],
    },
    resolve: {
        extensions: ['.ts', '.js'],
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: path.resolve(__dirname, 'src/index.html'),
            filename: 'index.html',
        }),
    ],
};

bootstrap.ts

import('./index').catch(e => console.error('Error importing `index.js`:', e))

Detailed solution can be found at: webpack-web-assembly-rust-impl-bug

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class: class Dataframe extends Object { _nrow: number; _ncol: number; _identity: number[]; co ...

Is it possible to generate a user profile using Firebase Cloud Functions and assign the user id as the document id?

I'm having trouble generating a user profile document in Firebase cloud functions using the user.uid as the doc id. Below is the script I am working with, but it keeps failing. I suspect there might be a syntax issue, so any suggestions would be great ...

Here's a unique version: "Utilizing the onChange event of a MaterialUI Select type TextField to invoke a function."

I am currently working on creating a Select type JTextField using the MaterialUI package. I want to make sure that when the onChange event is triggered, it calls a specific function. To achieve this, I have developed a component called Select, which is es ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...

Navigating with Angular: Transmitting dynamic URL parameters to components

I currently have the following routes defined: const routes: Routes = [ { path: ':product/new', children: [{ path: 'std/:country', component: SignUpComponent, data: { ...

Using forEach in React to simultaneously set multiple properties and return destructured output within the setState function

The following is the initial code snippet: setRows((rows) => rows.map((row) => selected && row.node === selected.id ? { ...row, row.a: "", row.b: "", row.c: "" } ...

Why did the compilation of Next.js using TypeScript and ESLint succeed despite encountering errors?

I've been delving into Next.js and encountered unexpected results when integrating TypeScript and ESLint. ESLint seems to work well with TypeScript, but my project compilation is successful despite encountering errors. It's puzzling why the comp ...

Vue does not recognize the Nuxt $route

Greetings, I've encountered a strange issue. I'm working on a Nuxt app with Typescript. In the created hook, I am using console.log to log this.$route. The log is functioning correctly and I am able to read the params from the route. However, d ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

the process of accessing information from a service in an Angular Typescript file

After making a POST request using Angular's HTTP client, the response data can be accessed within the service. However, is there a way to access this data in the app.component.ts file? I am able to retrieve the response data within the service, but I ...

What is causing the incompatibility of these generic props?

I am encountering compatibility errors when using two React components that have props accepting a generic parameter TVariables. These props include the fields variables of type TVariables and setVariables of type (vars: TVariables) => void. Even thoug ...

Can default values be assigned to a DTO during initialization?

What is the method to assign default values when a query is empty? In the case where I have this DTO structure for a query: export class MyQuery { readonly myQueryItem: string; } If the request doesn't include any query, then myQuery.myQueryItem ...

Troubleshooting an angular problem with setting up a dynamic slideshow

I am currently working on building a slideshow using plain HTML, CSS, and JavaScript. I referred to the following example for guidance: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto However, despite implementing the code prov ...

Unable to utilize Google Storage within a TypeScript environment

I'm encountering an issue while attempting to integrate the Google Storage node.js module into my Firebase Cloud functions using TypeScript. //myfile.ts import { Storage } from '@google-cloud/storage'; const storageInstance = new Storage({ ...

Trouble implementing array filter in React component is a common issue

Hello everyone! I'm facing an issue with deleting an element from my useState array. I have the index of the element that I want to remove, and I've tried the following code snippet: const updatedArray = myArray.filter((item: any, index: number) ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Enhance Your NestJS Application by Extending Mongoose Schemas and Overriding Parent Properties

In order to achieve the desired functionality, I have a requirement for my Class B to extend a Class A. This initial step works as intended; however, the next task at hand is overriding a property of Class A within Class B. More specifically, it is necess ...

Mapping an HTTP object to a model

Currently facing an issue with mapping an http object to a specific model of mine, here is the scenario I am dealing with: MyObjController.ts class MyObjController { constructor ( private myObj:myObjService, private $sco ...

Encountering difficulties during the migration process from a JavaScript to a TypeScript React Component

I've encountered some challenges with configuring TypeScript in my project. Initially, I developed my application using plain JavaScript. However, eager to learn TypeScript, I decided to convert my JavaScript project into a TypeScript one. To achiev ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...