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
Top comments (7)
This not only is very hacky, but the official rustwasm.github.io site has better ways of doing this.
Can you explain to me why it is 'very hacky' in your opinion and why my solution for linking TS + Rust + WebComponents is worse?
If you go through the trouble of adding webpack then why wouldn't you use the wasm-pack-plugin? In the approach that you have mentioned, you will have to compile your code manually everytime you make changes in your rust code. I mean no disrespect but the steps I am mentioning are mentioned in the wasm-pack document itself. Hope this answers your question. :)
There are better ways to provide improvement suggestions on such an edge case.
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?
Planning to write react code in Rust?? A really strange question.