Lazy values
Sometimes you can only get a value after the module where it should be serialized to is created. When using the AIK Plugin, for example, you can only define an inline module during the astro:config:setup
hook, but you might want to serialize a value from other hooks.
For such use cases, you can use the lazyValue
utility to create a placeholder value that you can set later:
Under the hood
Internally this utility will park the module inspection and serialization in Node’s event loop such that it can be resumed once, and only once, the value of the lazy value is set. This allows for as much of the inspection/serialization work to be done preemptively, and not wait for the value to be set.
During the module resolution, anything awaiting on the load
event of the virtual module will also be parked until the value is set.
Requirements
When using lazyValue
you must provide the following guarantees:
- The value is set on all possible code paths
- The value is set before Vite’s bundling is expected to complete (and here we say expected because if you don’t set the value, Vite will never complete the bundling)
- The value being set does not depend on resolving the serialization of the value (neither directly or indirectly)