How to bundle Wasm in npm package

Introduction

Premise

Creating npm package

$ ls resources/
custom_opencv-simd.js custom_opencv-simd.wasm custom_opencv.js custom_opencv.wasm
rules: [
{ test: [/\.ts$/], loader: "ts-loader" },
{ test: /\.wasm$/, type: "asset/inline" },
],
import * as tf from '@tensorflow/tfjs';

import opencvWasm from "../resources/custom_opencv.wasm"; // <------ (1)
import opencvWasmSimd from "../resources/custom_opencv-simd.wasm"; // <------ (1)


export class CustomOpenCV {
opencvLoaded = false;
wasm: Wasm | null = null;

init = async (useSimd: boolean) => {
const browserType = getBrowserType();
if (useSimd && browserType !== BrowserType.SAFARI) {
const modSimd = require("../resources/custom_opencv-simd.js"); // <------ (2)
const b = Buffer.from(opencvWasmSimd.split(",")[1], "base64"); // <------ (3)
this.wasm = await modSimd({ wasmBinary: b }); // <------ (4)
} else {
const mod = require("../resources/custom_opencv.js"); // <------ (2')
const b = Buffer.from(opencvWasm.split(",")[1], "base64"); // <------ (3')
this.wasm = await mod({ wasmBinary: b }); // <------ (4')
}
};

predict = async (targetCanvas: HTMLCanvasElement, th1: number, th2: number, apertureSize: number, l2gradient: boolean) => {
<snip>
};
}

Creating Application using this npm package

import { CustomOpenCV } from "opencv-lib";

const App = () => {
const opencvLib = React.useMemo(() => {
const lib = new CustomOpenCV();
lib.init(false);
<snip>

Repository

Finally

I am very thirsty!!

--

--

--

Software researcher and engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CRA to PWA 😎

Runing Demo of Amazon Chime SDK

What Makes React Native A Better Option for Startups?

Create a custom directive in Angular 2 application.

Intercept and manipulate requests with Puppeteer and Playwright

Hotwired ASP.NET Core Web Application — Part 5

Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha

Geocoding using Mapbox, Rails 5 and NuxtJS/VueJS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
dannadori

dannadori

Software researcher and engineer

More from Medium

Implementation of Server-Side-Rendering

Next.JS dynamic image resizer is a game changer

Firestore -in- subscription with more than 10 elements

How to implement a tracking log output location plugin?