I created a repository with example project which you can find here: web-assembly-rust-typescript-template
What you will need:
How to set up project
Set-up
Web - TypeScript part
-
Initialize npm project
npm init -y
-
Install the following dependencies
npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin ts-loader typescript
-
Create
index.js
file and export your App (this will be an entry point of your application)
export { App } from './App';
-
Create
bootstrap.ts
file in which you will import yourindex.js
asynchronously. We have to load the app asynchronously because.wasm
files have to be loaded asynchronously
import('./index').catch(e => console.error('Error importing **index.ts**:', e));
-
Create
webpack.config.js
. Here we have to useexperimetns: syncWebAssembly
to load our.wasm
files
experiments: { syncWebAssembly: true }
-
Add
serve
andbuild
script to yourpackage.json
"scripts": { "serve": "webpack serve", "build": "webpack" }
WebAssembly - Rust part
-
In root of your project create wasm project using
wasm-pack
wasm-pack new name-of-package
-
Go to package directory
cd ./name-of-package
Run
wasm-pack build
to build your wasm package
Link wasm-package with TypeScript code
-
Install your wasm package (if you publish your wasm package then you can install it via
npm
)
npm install wasm-package-name/pkg
-
Make sure that you can find this dependecy in your
package.json
"dependencies": { "wasm-package-name": "file:./wasm-package-name/pkg" }
Make sure you have
"moduleResolution": "node"
in yourtsconfig.json
Summary
If you followed all those steps you should have all typing hints from your wasm-package in your typescript project
Discussion (2)
Can you explain why you would need both Typescript and Rust for a WebAssembly project? Either AssemblyScript or Rust can compile to WebAssembly, I would just choose one.
I am not sure did I understand your question, but I will try to answer. Why:
This post is not about: "Use Rust and WebAssembly over Vanilla JS in any case to boost your app performance" because it doesn't work like that. I just wanted to show how to combine these technologies so that they are pleasant to work with.
Have I answered your question?