syscall/js: JS Module Dynamic Imports?

210 views
Skip to first unread message

Eduard Castany

unread,
Sep 29, 2020, 4:13:03 AM9/29/20
to golang-nuts
In JavaScript we can import JavaScript modules statically and dynamically. How could we import a JavaScript module dynamically in Go?

The closest/simplest thing may be to add an HTML script tag into the page header programatically (and I'm going to try that) but maybe there is a more obvious way that I'm not seeing.

Alvadron

unread,
Sep 29, 2020, 5:44:56 AM9/29/20
to golang-nuts
This is what I have been doing and it has worked for my needs:
```
// Importing it using "require" and storing the module in a variable
core := js.Global().Call("require", "@boostercloud/framework-core")

// Now get some props/methods from that module as usual:
config := core.Get("Booster").Get("config")
```
Is this what you were asking about?

Eduard Castany

unread,
Sep 29, 2020, 8:54:52 AM9/29/20
to golang-nuts
I guess this works on node.js but I was referring to the browser environment. Where normal JavaScript can just `import("module")`.

Joop Kiefte

unread,
Sep 29, 2020, 10:34:13 AM9/29/20
to eduard....@gmail.com, golan...@googlegroups.com
I think that's pretty recent? The only way used to be to add a script tag, and I have used that in Go before. I think just putting it in as a function call might work though...
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/7a8c0562-ec87-47ae-a37e-207ca8a11483n%40googlegroups.com.

Eduard Castany

unread,
Oct 5, 2020, 2:03:25 PM10/5/20
to golang-nuts
So, adding <script type="module" src="lib.js"></script> to the header does NOT seem to import anything into Go's wasm. I'm thinking that this is because modules do not have global scope so Go has to import them itself, rather than delegating the loading to JS, to be able to use them. Any ideas?

Joop Kiefte

unread,
Oct 5, 2020, 2:47:17 PM10/5/20
to eduard....@gmail.com, golan...@googlegroups.com
the environment of the wasm decides what you have access to, so you might want to add the import in the HTML around it instead.

pq35q
Reply all
Reply to author
Forward
0 new messages