tc39 / proposal-built-in-modules

BSD 2-Clause "Simplified" License
892 stars 25 forks source link

Future extension to support lazy built-in module loading #63

Open littledan opened 3 years ago

littledan commented 3 years ago

Normal JS modules only execute their top-level statements if someone imports them. In this proposal, if you want to polyfill built-in modules, you have to call BuiltinModule.export eagerly, just in case, and maybe that work will be wasted. This seems like a reasonable option for an MVP, so I support this proposal going to Stage 2 as is.

If we wanted to support a future extension for lazy built-in module polyfilling, we could make an alternative export API--call it BuiltinModule.exportLazy, which expects a callback, which is called at most one time, that returns the exports object. This callback will be called by the system when/if anyone imports the module--whether though BuiltinModule.import(), an import statement, or a dynamic import(). If polyfill authors decide to use this API, it could improve load performance by executing less code.

ljharb commented 3 years ago

Polyfilling is rarely as simple as “it’s absent, here’s a replacement” - it quite often requires inspecting the existing builtin and selectively polyfilling/wrapping/patching it. In practice i don’t think there would be a measurable benefit from optimizing for this rare use case (when you don’t need the runtime value in order to decide what to polyfill)

littledan commented 3 years ago

I guess it probably depends on the case. I understand that some polyfills aim to add features added over time or correct browser bugs. I believe others don't, and just try to fill in the feature overall. Anyway, even if you're wrapping, I think it would make sense to do this lazily--we'd just have to make sure that the "underlying"/previous module is sent as a parameter to the callback. This only really falls over if you have a bunch of interdependent modules (which I admit may happen over time).

As I said, I'm fine with this API being a follow-on proposal, or deprioritized completely, but I wanted to talk about this possibility, just to make sure that built-in modules would be future-proofed against this possibility.

guybedford commented 3 years ago

I really like @littledan's suggestion of being able to lazily define builtins - this seems like it could make platform boot time much faster in not needing to initialize entire components of the platform until explicitly needed.

Jack-Works commented 3 years ago

I think this is a must for this proposal. #67 might be a solution for this