Encountered issues while trying to utilize wasm function within Vue framework

When attempting to integrate wasm with Vue, I encountered a frustrating issue where the startQuorum function in my wasm file could not be located.

import { Go } from './wasm_exec'
import quorumWasmUrl from './lib.wasm'

export const startQuorum = async (bootstraps: Array<string>) => {
  const go = new Go()
  WebAssembly.instantiateStreaming(fetch(quorumWasmUrl), go.importObject).then(
    async (result) => {
      go.run(result.instance)
      const StartQuorum = result.instance.exports.StartQuorum as CallableFunction
      // StartQuorum is a function. but ts can not find it.
      await StartQuorum('password', bootstraps.join(','))
    }
  )
  console.log('startQuorum over')
}

The wasm files were written in Go, and the original function looked like this:

js.Global().Set("StartQuorum", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        if qChan == nil {
            qChan = make(chan struct{}, 0)
        }

        // Rest of Golang code omitted for brevity

    }))

Even though the StartQuorum function existed in the wasm file, TypeScript was unable to locate it, resulting in the following error message in the browser:

Uncaught (in promise) TypeError: StartQuorum is not a function
at eval (load-quorum.ts?b7b7:139:1)

Although the wasm file loaded successfully, initial troubleshooting suggested that TypeScript was not recognizing functions within the wasm file.

How can this issue be resolved?

Answer №1

The reason for this behavior is due to the fact that it's not an exported function. The Golang Compiler does not currently support exporting functions, only importing them using the magic CALLIMPORT assembly instruction. It's worth noting that this limitation applies specifically to the Golang Compiler, and other compilers like TinyGo may behave differently.


To work around this limitation, you can use js.Global().Set to set the function within the js.Global() object, which is essentially the equivalent of window/globalThis:

js.Global().Set("StartQuorum", ....)

This will create the StartQuorum function at the window/globalThis level, allowing you to call it using window.StartQuorum().


In light of this, the line:

const StartQuorum = result.instance.exports.StartQuorum as CallableFunction
// StartQuorum is a function. but ts can not find it.

await StartQuorum('password', bootstraps.join(','))

Seems illogical, as

result.instance.exports.StartQuorum
always returns null. Your function actually resides in window.StartQuorum or globalThis.StartQuorum (...).

This means it is not an exported function from WebAssembly (which would be found in result.instance.exports).

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

The potential for an 'undefined' object in TypeScript React is a concern that should be addressed

Currently, I am honing my skills in using TypeScript with React and retrieving data from an API that I set up a few days back. The API is functioning properly as I am able to fetch data for my front-end without any issues. However, when I attempt to util ...

Tips for displaying CSS recommendations in JetBrains IDE (such as PyCharm) for your Nuxt project

Can anyone provide guidance on how to display CSS suggestions in JetBrains IDE (such as PyCharm)? They work fine in normal Vue projects with Vuetify, but for some reason they are not appearing in my Nuxt project. I currently have them working in my Vue pr ...

What is the most effective way to reset the v-model in the child component using the parent component?

Could you please assist me? I have been trying for 10 hours straight and it doesn't seem to work. What I am aiming for is that when I click on @click="cleanDataForm" in the Parent Component, the v-model text in the Child component will be emptied. I h ...

What could be causing the discrepancy in alignment between a web application running on Mac and Windows using ReactNative?

We have a web application built with react native. The alignment of the columns in the list is causing issues when running the app on Windows versus Mac, as illustrated in the screenshots. Interestingly, this problem only occurs with this specific list tha ...

Guide to Implementing Vuetify within a Laravel 9 Vue SPA

My original intention was to integrate vuetify into my app. However, after installing the necessary packages and configuring resources\js\app.js, I encountered a runtime error: Uncaught TypeError: vue__WEBPACK_IMPORTED_MODULE_0___default.a is und ...

The hyperlink within the Angular component seems to be unresponsive and is difficult to click on

I attempted to click on the user's profile link, but nothing happens. It seems impossible to interact with it. Here is the code snippet: JavaScript ViewUserProfile(user) { this.router.navigate([user.username]); if (this.currentUser.usernam ...

What sets apart 'export type' from 'export declare type' in TypeScript?

When using TypeScript, I had the impression that 'declare' indicates to the compiler that the item is defined elsewhere. How do these two seemingly similar "types" actually differ? Could it be that if the item is not found elsewhere, it defaults ...

Guide to effectively utilizing Vue slot-scope feature within nested components

I am currently facing difficulties in understanding the proper usage of the slot-scope attribute and comprehending the documentation. Below is a simplified version of my requirement. You can view it in action here: https://jsfiddle.net/4j4zsy0g/ Main Cod ...

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

Angular project service file experiencing issues with TypeScript string interpolation functionality

Here is the code snippet for a service in an Angular project: @Injectable() export class FetchDataService { fetch(link){ console.log('This is a ${link}'); } } In my component, I am invoking this method with a string parameter. Upon che ...

When transitioning to angular 10 and removing decorators from classes, what is the best approach for dealing with a base class that is inherited by both Directives and Injectables?

During the angular 10 migration process, there is a recommendation that classes utilizing angular features should have a decorator. However, what should be done in cases where it's a base class shared by both Injectables and Directives (as it solely i ...

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

Error TS2315: Invalid Type Assignment for Angular 6 ModuleWithProviders

Hey there, I'm encountering an issue that's got me scratching my head. I've shared some of my code in the hopes that it might shed some light on the problem. The problem cropped up as soon as I started working on a Reactive Form. Let me s ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...

Mastering asynchronous props handling with Vue 3's composition API

Starting Component: const { receiveData, deletePost, erasePhonebook, fetchCount, issue } = useSections(); const section = ref({}); receiveData(section_id).then((s) => { section.value = s; }); Sub Component: const { section } = defineProps({ secti ...

What techniques can be employed to dynamically modify Typescript's AST and run it while utilizing ts-node?

Below is my approach in executing a TypeScript file: npx ts-node ./tinker.ts In the file, I am reading and analyzing the Abstract Syntax Tree (AST) of another file named sample.ts, which contains the following line: console.log(123) The goal is to modify ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

Observing for form input in Nuxt.js

There is a form on my webpage, which includes the following elements: <div v-if="this.userdata.address == ''">Please enter your address</div> Your address <input type="text" v-model="userdata.address" ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...