Are ES6 modules in browsers going to get loaded level-by-level?

Randy Buchholz work at randybuchholz.com
Sat Oct 24 21:36:27 UTC 2020


>Like, extending from a Module object?

No, it’s more when I derive from an imported class. I had a “ReceivePort” module and a “SendPort” module that both use a base class “CommPort”. Since a module “seems to be” an isolated scope I thought I could extend CommPort individually inside each module. I knew the browser cached the download, but didn’t know about it caching a ”live” object. 

This isn’t exactly what I was doing, but it close to the idea.

```
Module: CommPort
class CommPort {
    set duplexHost(host) { … }
}

// Module: ReceivePort
import { CommPort } from…
class ReceivePort extends CommPort { }

// Module: SendPort
import { CommPort } from…
class SendPort extends CommPort { }

// Module: DuplexPort
import { SendPort } from…
import { ReceivePort } from…

class DuplexPort {
    #sendPort = new SendPort();
   #receivePort = new ReceivePort();
    constructor(){
        sendPort.duplexHost = this;
        receivePort.duplexHost = this;
          } 
}
```
I have “Worker Farms” where each worker has multiple `DuplexPort` to communicate with other workers.  I would send a message to one worker and pretty much all of them received the message. The problem wasn’t obvious to me, especially since I was generally new to ES at the time.

What happens is the browser downloads `CommPort` once, and also creates a single `CommPort` object. All of the scoped `CommPort` objects are just pointers to that. So the imported `CommPort` in `SendPort` is the same `CommPort` as the one in `ReceivePort`. When the `DuplexPort` registers itself on the ports (even though it seems isolated within a module scope) the registration “leaks” up to the live ghosted `CommPort`. Every message was going through the last port registered! This is one reason for the approach I’m taking. When I `inject` I get a “clean” base class to inherit from.


More information about the es-discuss mailing list