Go每日一库之136:gopherjs(将Go代码编译成JS)

2023-09-30 08:49:27 浏览数 (1)

简介

GopherJS 可以将 Go 代码编译成纯 JavaScript 代码。其主要目的是为了让你可以使用 Go 来编写前端代码,这些代码可执行在浏览器上运行。你可以通过这里尝试下 GopherJS: GopherJS Playground.

例如 JavaScript 代码: document.write("Hello world!");

用 GopherJS 来写就变成这样: js.Global.Get("document").Call("write", "Hello world!")

好像复杂了不少,函数调用这样:

代码语言:javascript复制
package main

import "github.com/gopherjs/gopherjs/js"

func main() {
  js.Global.Set("myLibrary", map[string]interface{}{
    "someFunction": someFunction,
  })
}

func someFunction() {
  //...
}

安装

代码语言:javascript复制
go get -u github.com/gopherjs/gopherjs

// or

go install github.com/gopherjs/gopherjs@latest

简单Demo

进行pi 运算,结果还真是快

代码语言:javascript复制
package main

import (
	"fmt"
	"math"
	"time"
)

func term(k float64) float64 {
	return 4 * math.Pow(-1, k) / (2*k   1)
}

// pi performs n iterations to compute an approximation of pi using math.Pow.
func pi(n int32) float64 {
	f := 0.0
	for k := int32(0); k <= n; k   {
		f  = term(float64(k))
	}
	return f
}

func main() {
	// Start measuring time from now.
	started := time.Now()

	const n = 50 * 1000 * 1000
	fmt.Printf("approximating pi with %v iterations.n", n)
	fmt.Println(pi(n))

	fmt.Println("total time taken is:", time.Since(started))
}

一般我们使用go run 运行code; 但是使用gopherjs 我们用 gopherjs run。

运行:

代码语言:javascript复制
$ go run main.go

approximating pi with 50000000 iterations.
3.1415926735902504
total time taken is: 5.823561654s
代码语言:javascript复制
$ gopherjs  run  main.go

gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.
approximating pi with 50000000 iterations.
3.1415926735902504
total time taken is: 2.534s

web 场景应用(主要是一些bindings)

代码语言:javascript复制
package main

import (
	"fmt"

	"github.com/gopherjs/gopherjs/js"
)

func main() {
	fmt.Println("Hello, playground")
	js.Global.Call("alert", "Hello, JavaScript")
	println("Hello, JS console")
}

编译为JS代码:

代码语言:javascript复制
gopherjs build app.go

html 页面引用:

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="./app.js"></script>
</body>
</html>

打开html:

适用场景

后端golang 编写一次,多次使用,同时性能还不错,目前官方提供了好多方便的binding。 比如基于electron 开发的应用使用 gopherjs-electron会有比较大的性能提升,很不错的项目。

References

https://github.com/oskca/gopherjs-electron https://github.com/gopherjs/gopherjs https://github.com/rongfengliang/gopherjs-demo

0 人点赞