Compiling Go to Web Assembly in PowerShell
Posted on
I've been learning Go lately, and I wanted to experiment with web assembly as well. I whipped up an example that will pass a user-specified message to a WASM function, which will return a JSON object containing the value it received.
The command for compiling Go to web assembly without any tools like TinyGo is this:
GOOS=js GOARCH=wasm go build -o "./path/to/output/file.wasm" "./path/to/source/file.go"
That syntax works for Bash (and probably other Linux-based shells like Zsh, etc.), but I currently use PowerShell as my primary shell. I learned from this StackOverflow thread what the correct syntax for setting environment variables in PowerShell is:
$env:GOOS = 'js'; $env:GOARCH = 'wasm'; go build -o "./path/to/output/file.wasm" "./path/to/source/file.go"
For convenience, I wrote a PowerShell function to encapsulate that command:
This function sets the environment variables and compiles the code in a child process or "subshell" so the variables don't overwrite any that may already be set in the current shell. Place this function in your PowerShell profile to use it.