From TypeScript to WebAssembly in few steps
By: Kesk - -
Tags: JavaScript, Webassembly, Web Development, Typescript, Wasm

From TypeScript to WebAssembly in few steps

How to build your first Program in WebAssembly

Photo by Pixabay

In this article, I will show you how to compile a TypeScript program to WebAssemby that prints the factorial of a number.

I will write it using TypeScript and then compile it with AssemblyScript, which compiles a strict variant of TypeScript to WebAssembly(Wasm) using Binaryen.

WebAssembly is current an MVP and only handles integers and floats and doesn’t natively support strings or other types. For this reason, instead of the typical HelloWorld that uses Strings, I will write a function that takes in a parameter of the numerical type and that returns its corresponding factorial.

Why Wasm?

One of the most common reasons for use WebAssembly is its speed. Speed in a specific context is essential and can justify the sacrifice of other factors like developer experience, reliability, or maintainability. So, be careful.

Create the Factorial function in TS

Our factorial.ts file exports a factorial function that takes in a number value and returns the corresponding factorial number.

factorial.ts file

export function factorial(num: i32): i32 {

if (num === 0){

return 1;

}

else {

return num * factorial( num - 1 );

}

}

Compile the TypeScript factorial function to Wasm

In this step, I will compile it into a wasm module, using the AssemblyScript Compiler, which will output the corresponding factorial.wasm file.

First, I’m going to install the compiler as a global npm package so I can use it easily(You need to have npm installed on your computer):

npm i -g assemblyscript

Once the compiler is installed, we can use it with the command <asc sourceFile.ts destinationFile.wasm>:

factorial.wasm

asc factorial.ts -b factorial.wasm

Integrate All

Next, I’m going to create a factorial.js JavaScript file and add a function for loading Wasm modules using the WebAssembly Web APIs:

factorial.js

export const wasmInstantiate

= async (wasmModuleUrl, importObject) => {

let response = undefined; if (!importObject) {

importObject = {

env: {

abort: () => console.log("Error!")

}

};

} const instantiateModule = async () => {

//1.

const response = await fetch("./factorial.wasm");

const buffer = await response.arrayBuffer();

//2.

const obj = await WebAssembly.instantiate(buffer, importObject);

return obj;

}; response = await instantiateModule(); //3.

return response;

}; //...

I’m going to use the Fetch method to download the module. Here, we instantiate the Wasm module. Return the Wasm module.

factorial.js part 1 file.

//... const executeWasmFactorial = async () => {

//1.

const wasmModule

= await wasmInstantiate("./factorial.wasm"); //2.

const factorialResult

= wasmModule.instance.exports.factorial(7); //3.

document.getElementById("factorialResultId").innerHTML

= `The result is: <strong>${factorialResult}</strong>`;

}; executeWasmFactorial();

Instantiate the wasm module. Call our factorial function export from Wasm. Set the result to our HTML “factorialResultId” element.

factorial.js part 2 file.

joining all:

factoria.js complete file

Index.html

Finally, I have to load our factorial.js file in our index.html as an ES6 module:

<!DOCTYPE html> <html>



<head>

<meta charset="UTF-8" />

<title>Factorial - AssemblyScript</title>

<script type="module" src="./factorial.js"></script>

</head> <body>

<div id="factorialResultId"></div>

</body> </html>

index.html file.

Final folder structure

folder structure.

Summary

From TypeScript to Wasm byte code.

The TypeScript file with the factorial function that calculates the factorial of a number. Compiles from a typescript file to a Wasm file. The Wasm module calculates the factorial of a number. The factorial.js file loads the Wasm module and executes the factorial function of number 7 from the Wasm module. The index.html file imports the factorial.js file. The browser.

Execute it

For simplicity, I’m going to use a zero-configuration command-line http server:

Execute http-server in the folder of the code.

npm i -g http-server http-server -p 82

The http-server running

Final result.

And we have a Wasm byte code Factorial program running.

Conclusion

In this article, I’ve developed an elementary example, but I think it serves to get an idea of its power.

But remember, although performance is an essential factor for any technology, I don’t believe it’s the most significant factor except in specific contexts.

Thanks for reading me!