Tips for invoking TypeScript code from Rust WebAssembly

Currently, I am considering transitioning a slow TypeScript library (jackson-js) to WASM using rust.

This particular library has various dependencies, like reflect-metadata for example.

These dependencies are already created and accessible on npmjs. The thought of developing such a dependency in rust seems daunting.

Is there a way to call an npm dependency from Rust (which will eventually be compiled into WASM)?

Perhaps by exposing some functions to the browser's window object (though this approach could potentially cause conflicts or security issues?) Any alternative methods?

Answer №1

Transforming your codebase to include all data types and functions from dependencies may seem daunting, but it is achievable. While it may require some effort, it is definitely within reach. For instance, when dealing with Reflect.defineMetadata() from the reflect-metadata package:

#[allow(non_snake_case)]
mod Reflect {
    use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = Reflect)]
        pub fn defineMetadata(metadataKey: &str, metadataValue: JsValue, target: &JsValue);
    }
}

You can adapt all functions, even ones like Node.js' require(), in a similar manner. Take cues from established libraries like js-sys and web-sys to understand how they declare functionality.

It's important to note that reflect-metadata is primarily a reflection library for JavaScript, not specifically built for WASM. Its utility may be limited when attempting to add metadata to Rust objects instead of JS objects.

Moreover, if your code heavily relies on JavaScript libraries, transitioning to WASM may not necessarily result in a speed enhancement; in fact, it could potentially slow down the process. Improved performance with Rust and WASM is typically seen in scenarios involving intensive computations or memory allocation that can be optimized efficiently.

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

Error: The last line is missing a trailing comma

I'm struggling to understand why my tslint insists on having a trailing comma at the end of the last line in the objects. Is there a way to configure the ignore rule for the last line of objects? Appreciate any help! For example: settings = { ...

Combining Typescript Declarations for Express Request Object with Passport.js User/Session Integration

In my express/nodejs app, I am encountering issues with properties on the request.user object even after implementing Declaration Merging for authentication using passportjs middleware. To address this, I created a file at /types/index.d.ts in the project ...

Using a single Material Autocomplete input to handle two values within Angular

Looking to implement a search feature using Material's autocomplete that can filter by either user name or user ID. The current implementation is partially functional in this Stackblitz. When selecting a user name from the autocomplete options with a ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

The ts-mocha test does not play well with the use of node-fetch library

I have set up ts-mocha and node-fetch to run a unit test, but I am encountering the following error: TypeError: Unknown file extension ".ts" for ... The content of the file is as follows: import fetch from 'node-fetch'; export defau ...

Generic parameter with a union type

The proxy function returns a randomly determined type. const numbersArray = [1,2,3,4]; const stringsArray = ['1','2','3','4']; function func<T>(array: T[]): T[][] { return [[array[0], array[1]], [array[2], ...

Error encountered: The database is not found during the migration creation process in MikroORM

Attempting to create migrations with mikroORM has been a challenge as I am unable to generate the table itself. The error message indicating that the database "crm" does not exist leaves me puzzled about what steps I may have missed. Here is the code snip ...

How do AppComponent and @Component relate to each other in AngularJs 2?

Recently, I came across the file app.component.ts in Example and found some interesting code. The link to the example is: here. Here's a snippet of the code: import { Component } from '@angular/core'; export class Hero { id: number; na ...

The Jest test is experiencing a failure as a result of an imported service from a .ts file

In my Jest test file with a .spec.js extension, I am importing an index.js file that I need to test. Here is the code snippet from the .spec.js file: var HttpService = require('./index.js').HttpService; The problem arises because the index.js f ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...

Enhancing IntelliSense to recognize exports specified in package.json

I have a package.json file where I define various scripts to be exported using the exports field. "exports": { ".": { "default": "./dist/main.es.js", "require": "./dist/main.cjs.js", ...

The challenges of dealing with duplicate identifiers caused by nesting npm packages in TypeScript

I am facing an issue with my project structure where I have a node_modules folder at the root level and another one within a subfolder named functions. The directory layout looks like this, ├── functions │   ├── index.js │   ├── ...

A guide on exposing TypeScript classes globally through a WebPack bundle in JavaScript

Currently delving into TypeScript, my aim is to gradually replace JS with TS. However, due to having numerous JS files, my strategy involves creating new classes in TS and incorporating them into my existing JS files for the time being. Eventually, I plan ...

Unable to access global functions in Typescript

My current setup involves using cloudflare workers with miniflare. I have structured a bindings.d.ts file as follows: export interface Bindings { ENV: string MYSQL_URL: string JWT_SECRET: string JWT_ACCESS_EXPIRATION_MINUTES: number JWT_REFRESH_E ...

Leveraging constructors for injecting dependencies in Angular is a key practice for enhancing modularity and maintainability

After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this is utilized, while other times it is not. This leads to the que ...

Developing a custom React hook that utilizes the useContext functions

When attempting to utilize a function within a custom hook, I encounter the following error message: Error: tglCartao is not defined The custom hook code in UseCartao.tsx is as follows: export interface ICartaoContext { idToggleKey : string; ...

Exploring Sequelize: Uncovering the Secret to Retrieving Multiple Associated Items of Identical Type

Within my database, I have a situation where there are two tables sharing relations of the same type. These tables are named UserCollection and ImagenProcess UserCollection has two instances that relate to ImagenProcess. Although the IDs appear unique whe ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

There was an error in the CSS syntax in the production environment due to a missed semicolon

Trying to execute the npm build command "webpack --mode=production --config ./config/webpack.config.prod.js" on our project results in an issue. The issue arises when I include the bootstrap file in my tsx file as shown below. import bs from "../../../../ ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...