基本环境
有时需要做一些前端的数据处理,但是又不想把数据出来的方式就这么简单的暴露在js里,然后就用了wasm来包装这个处理函数,当然,这样也能提高性能。
新建文件 index.js
const fastify = require('fastify')({ logger: true }) const path = require('path') // Serve the static assets fastify.register(require('fastify-static'), { root: path.join(__dirname, ''), prefix: '/' }) const start = async () => { try { await fastify.listen(8080, "0.0.0.0") fastify.log.info(`server listening on ${fastify.server.address().port}`) } catch (error) { fastify.log.error(error) } } start()
package.json
{ "scripts": { "dev": "node index.js" }, "dependencies": { "fastify": "^3.6.0", "fastify-static": "^3.2.1" } }
index.html
hello hello
运行 npm run dev 打开http://127.0.0.1:8080
wasm部分
新建 go.mod
module hello-world go 1.18
main.go
package main import ( "syscall/js" ) func main() { message := " Hello World " document := js.Global().Get("document") h2 := document.Call("createElement", "h2") h2.Set("innerHTML", message) document.Get("body").Call("appendChild", h2) <-make(chan bool) }
运行 go env
win下
GOOS=windows
GOARCH=amd64
需要配置环境变量为 win 下设置 cmd运行 set GOOS=js
set GOARCH=wasm
生成必要文件(cmd会报错 powershell可以执行) cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
会多出一个wasm_exec.js
的文件
go打包成wasm 运行go build -o main.wasm
运行结束后会生成一个名为main.wasm
的文件
然后修改之前的index.html
文件
WASM
然后刷新浏览器就能看到这么一个界面
以上就是go打包网页wasm示例详解的详细内容,更多关于go打包网页wasm的资料请关注脚本之家其它相关文章!