Giter Site home page Giter Site logo

happybeing / webpack-golang-wasm-async-loader Goto Github PK

View Code? Open in Web Editor NEW

This project forked from aaronpowell/webpack-golang-wasm-async-loader

5.0 2.0 4.0 674 KB

A webpack loader for generating Golang WebAssembly bundles using an async interaction model for calling the Golang code from JavaScript

License: MIT License

Go 4.60% JavaScript 81.04% TypeScript 14.36%

webpack-golang-wasm-async-loader's Introduction

[![Build Status][build]][build-url] npm node

Golang WebAssembly Async Loader

Generates a WASM package from Golang and provides an async interface for working with it

golang-wasm-async-loader2 is a fork of golang-wasm-async-loader updated for Golang v1.13

Install

npm install --save-dev golang-wasm-async-loader2

This is a loader for webpack that is used for generating WebAssembly (aka WASM) bundles from Go.

The JavaScript bridge that is then generated for webpack will expose the WebAssembly functions as a Promise for interacting with.

Note: This fork updated to with Go 1.13 or Go 1.15

webpack config

module.exports = {
    ...
    module: {
        rules: [
            {
                test: /\.go/,
                use: ['golang-wasm-async-loader2']
            }
        ]
    },
    node: {
        fs: 'empty'
    }
};

Using in your code

You import your Go code just like any other JavaScript module you might be working with. The webpack loader will export a default export that has the functions you registered in Go on it. Unfortunately it currently doesn't provide autocomplete of those function names as they are runtime defined.

import wasm from './main.go'

async function init() {
  const result = await wasm.add(1, 2);
  console.log(result);

  const someValue = await wasm.someValue();
  console.log(someValue);
}

Here's the main.go file:

package main

import (
  "strconv"
  "syscall/js"
  "github.com/happybeing/webpack-golang-wasm-async-loader/gobridge"
)

func add(i []js.Value) (interface{},error) {
	ret := 0

	for _, item := range i {
		val, _ := strconv.Atoi(item.String())
		ret += val
	}

	return ret, nil
}

func main() {
	c := make(chan struct{}, 0)

	gobridge.RegisterCallback("add", add)
	gobridge.RegisterValue("someValue", "Hello World")

	<-c
}

How does it work?

As part of this repository a Go package has been created to improve the interop between the Go WASM runtime and work with the async pattern the loader defines.

To do this a function is exported from the package called RegisterCallback which takes two arguments:

  • A string representing the name to register it as in JavaScript (and what you'll call it using)
  • The func to register as a callback
    • The func must has a signature of (args js.Value) (interface{}, error) so you can raise an error if you need

If you want to register a static value that's been created from Go to be available in JavaScript you can do that with RegisterValue, which takes a name and a value. Values are converted to functions that return a Promise so they can be treated asynchronously like function invocations.

In JavaScript a global object is registered as __gobridge__ which the registrations happen against.

Examples

Examples are provided for a CLI using NodeJS and for web using either React or Svelte. These are in the examples directory, each with its own development and build environment.

To make an example stand-alone, copy of the corresponding example to a new directory (outside the plugin directory) and then modify the example's webpack.config.js so that the .go loader refers to this plugin. Then add it to the example's dependencies as follows.

For use with Go 1.13 you must use v1.0.6 of the plugin:

npm add --save-dev [email protected]`

For use with Go 1.15 you must use v1.1.0 of the plugin:

npm add --save-dev [email protected]`

Environment

To build your project (and the examples) you will need the GOROOT environment variable set. So for example if using the bash shell:

node example:

GOROOT=`go env GOROOT` npm run predemo
npm run demo

web example (with hot reloading):

GOROOT=`go env GOROOT` npm run build
GOROOT=`go env GOROOT` npm run start

Licence

MIT

Credit

Aaron Powell (update to golang v1.13 by Mark Hughes)

webpack-golang-wasm-async-loader's People

Contributors

aaronpowell avatar happybeing avatar larcado avatar sudhanshug16 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

webpack-golang-wasm-async-loader's Issues

Support Go versions other than v1.13

v1.0.6 of this plugin only supports Go v1.13 due to the need to fix a problem in the distributed with this and current Go versions up to at least v1.15 (released November 2020).

Each Go version provides its own version of $GOROOT/misc/wasm/wasm_exec.js and these need a slight modification to work in certain environments (including with my p2p-git-portal-poc project). This appears to be fixed in Go commit golang/go@758ac37#diff-50c9536f867ce96d4731b5239b25952e38ad65800cebb9f76fbc880d34e62e94, but as of Go 1.15.5 this change has not been included in a release of the compiler.

The Fix

In order to work with Go v1.13 I had to modify the code which sets a property global.fs and tests whether or not to use the fs stub functions provided in wasm_exec.js. The error I was encountering was that these functions were NOT being used, leading to the following error on loading my Go/wasm app, when using the plugin:

Uncaught (in promise) TypeError: fs.writeSync is not a function
    wasmWrite wasm_exec.js:248
    run wasm_exec.js:475
    init gobridge.js:17
    default_1 gobridge.js:20
    go main.go:2
    Webpack 9

The diff between Go v1.13's wasm_exec.js and the one provided in this plugin is:

< 		global.fs = require("fs");
---
> 		// global.fs = require("fs");
> 		const fs = require("fs");
> 		if (Object.keys(fs) !== 0) {
> 			global.fs = fs;
> 		}
33c37
< 	if (!global.fs) {
---
> 		if (!global.fs || Object.keys(global.fs) === 0 || Object.keys(global.fs).length === 0) {

An equivalent fix appears to have been applied in this commit golang/go@758ac37#diff-50c9536f867ce96d4731b5239b25952e38ad65800cebb9f76fbc880d34e62e94 (Aug 25, 2020) but is not yet included in a release. Go 1.15 was release in August 2020. 1.16 will be six months after in February 2021.

The relevant commit is currently only in master, so presumably this change will appear in Go 1.16 (or possibly an point release of 1.15). The following checks which branches include this change:

git branch --contains 758ac371ab930734053ed226ac62681e62ab8eea

Once the fix is applied to the file distributed with Go, this plugin could just copy the compiler's file rather than use its own. This would be accomplished by the following edit of src/index.ts:
Replace:
join(__dirname, "..", "lib", "wasm_exec.js"),
with:
join(process.env.GOROOT, "/misc/wasm/wasm_exec.js"),

Plan (Feb 2021)

When Go v1.16 is released, test the plugin with the new unmodified wasm_exec.js, and if it works apply the above change so that:

  • Plugin ^1.2.0 - supports Go v1.16 and later
  • Plugin 1.0.6 - supports Go v.1.13 only

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.