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!!

--

--

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