1.安裝rustup
打開終端執(zhí)行下面命令
$ curl https://sh.rustup.rs -sSf | sh
重要:如果你沒有翻墻弦牡,會發(fā)現(xiàn)安裝不了
error: could not download file from 'https://static.rust-lang.org/dist/channel-rust-stable.toml' to '/Users/apple/.rustup/tmp/x3tlzua732gf0u19_file.toml'
info: caused by: error reading from socket
info: caused by: timed out
解決方法: 電腦連上手機(jī)熱點,再執(zhí)行命令curl https://sh.rustup.rs -sSf | sh
輸入1并回車
這說明已經(jīng)安裝完成漂羊,執(zhí)行下面命令使環(huán)境變量生效:
$ source $HOME/.cargo/bin
檢查rust環(huán)境變量是否生效:
$ rustc --version
2.創(chuàng)建config文件驾锰,路徑為$HOME/.cargo/config
,加入以下內(nèi)容
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
# replace with your favourite mirror
replace-with = 'sjtu'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
[source.sjtu]
registry = "https://mirrors.sjtug.sjtu.edu.cn/git/crates.io-index"
![image.png](https://upload-images.jianshu.io/upload_images/9960789-b07789080ae1b41f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
[source.rustcc]
registry = "https://code.aliyun."
3.安裝 cargo-generate
cargo-generate
是一個用于快速生成 WASM 項目的腳手架(類似 vue-cli)
$ cargo install cargo-generate
4.安裝 wasm-pack
wasm-pack
用于將 Rust 項目打包成單個 WASM 文件(類似 Webpack)走越,是wasm的打包工具
$ cargo install wasm-pack
5.創(chuàng)建wasm + rust項目
5.1 在根目錄通過創(chuàng)建工具創(chuàng)建一套rust的模板代碼, 命名為wasm-project
$ cargo generate --git https://github.com/rustwasm/wasm-pack-template
目錄如下
在這個項目的根目錄下執(zhí)行構(gòu)建命令來編譯我們的wasm文件
$ wasm-pack build
隨后生成了pkg文件夾椭豫,這下面就是我們的wasm項目編譯出來的文件
5.2 隨后我們創(chuàng)建一個文件來測試生成的wasm文件,在這個目錄下創(chuàng)建package.json文件
{
"name": "wasm-project",
"version": "0.1.0",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server --open"
},
"devDependencies": {
"hello-wasm-pack": "^0.1.0",
"webpack": "^4.16.3",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
"copy-webpack-plugin": "^4.5.2"
}
}
5.3 在這個目錄下創(chuàng)建webpack.config.js文件
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require('path');
module.exports = {
entry: "./test_wasm.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "test_wasm.js",
},
mode: "development",
plugins: [
new CopyWebpackPlugin(['index.html'])
],
};
5.4 創(chuàng)建test_wasm.js
import("./index.js")
.catch(e => console.error("Error importing `index.js`:", e));
5.5 創(chuàng)建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>hello rust</title>
</head>
<body>
<script src="./test_wasm.js"></script>
</body>
</html>
5.6 創(chuàng)建index.js
import * as wasm from "./pkg/wasm_project_bg.wasm";
wasm.greet()
5.7 執(zhí)行wasm-project項目
$ sudo npm install
$ npm start
5.8 在瀏覽器訪問 http://localhost:8080/
可以看到彈框
一個簡單的用rust寫的wasm項目運行起來了~
end------------------------------------------------------------------