Wasm Chinese materials are very limited, almost only the official website and nuggets have some articles, today I write this article to do the introduction of WASM documentary. As the underlying language of Firefox and a new project of Mozilla, Rust has a relatively good version processor rsutup, a powerful package manager cargo, and an active community of open source enthusiasts. It has better performance and better development experience than THE C language and is not much different from the development of Node.js projects. In the spirit of componentized modularity, this article will not cover the prerequisites for installing and briefly learning Rust.
- The default you have
Rust
andnode
thetools
:restup
Rust version management softwarecargo
A package managerrustc
Compilers seem to look the samejavac
node.js v.14+
npm/yarn
git
Basic front-end tools
The following build is very similar to the Build for the Node project
detectiontools
:
rustup --version
rustc --version
cargo --version
Copy the code
If you have the following result, you already have a running environment
Rustc 1.54.0 a178d0322 (2021-07-26)Copy the code
When your version number is much larger than this, this article may have an error! (We can only hope that the developer is backward compatible)
downloadwasm-pack
package
There are two ways to download it
- through
cargo
cargo install wasm-pack
Copy the code
- Download from the Internet
Download githubuserContent.com and open it.
Build the underlying Rust Package
Install the code generator:
cargo install cargo-generate
Copy the code
Sample code using documentation
cargo generate --git https://github.com/rustwasm/wasm-pack-template
Copy the code
This means that using the cargo generate tool does not need to use git to crawl code.
After the building:
- src Source code file
- lib.rs Write the main WASM code
- util.rs Code exception handling alternative functions
- .travis.yml *
- Cargo.toml *
- LICENSE_APACHE *
- LICENSE_MIT *
- README.md *
- tests The test file
No need to edit the code
Document Content Interpretation
Package executable WASM files
wasm-pack build
Copy the code
The PKG folder appears after build, which contains the executable.wasm,.d.ts,.js, and package.json files. Very friendly to front end players.
Debugging locallywasm
Setting up a local server
mkdir www # same as PKG folder
cd www
npm init wasm-app
npm install
Copy the code
After executing the above command, you should have a regular Node.js project file managed by WebPack that supports HTTP access.
It seems that because of my webpack version, import wasm is always wrong in index.js
So I just changed it
import * as wasm from ".. /pkg";
wasm.greet();
Copy the code
perform
npm run start
Copy the code
You can access it at http://localhost:8080 and see a hello_wasm alert().