feat: pre transform direct imports before requests hit the server #5037
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently Vite only transforms a file (i.e. go through the plugin pipeline) when the file is requested. This ensures only files actually used on the current page are transformed, however it also creates a problem with deeply nested import chains:
B
is only requested whenA
is evaluated in the browser (triggering the import request toB
). SimilarlyC
is only requested afterB
is evaluated in the browser. The problem becomes more obvious when there are many modules being loaded in parallel - since the browser typically can only handle 6 parallel requests so it will hold off some requests until previously pending requests have resolved (HTTP/2 requires HTTPS which in fact make things slower). This causes requests to hit the server at a delayed rate so the server is in fact under-utilized and waiting for the browser. The deeper the import chain and the more modules are loaded in parallel, the more obvious the problem is.Since Vite already performs import analysis when transforming each module, we can in fact start transforming all direct imports of a module before even sending back the response. This essentially means Vite will be eagerly compiling the non-lazy-imported sub graph of the application without waiting on network requests. When the requests come in, they can pick up the already initiated transform Promise (can be pending or already resolved).
I did some synthetic benchmarking here:
Tests are passing but this may have subtle implications in real world cases, so we should put it in a beta and test it in some projects to make sure it doesn't break anything.