feat: Allow importing client modules from server code #15202
+1,487
−1
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.
(copying from the first commit message)
Vite includes a feature that allows importing a module's URL to then later dynamically load it. In development mode, you can use this to get the import path for a module on the server, and return it to the client to load.
Unfortunately, in release mode this doesn't work because the client build and the server build are two different runs. This adds a Vite plugin that stubs out these imports in the server build, and adds the imported path as an entrypoint to the client build, allowing the same effect. See the end-to-end test for a demonstration.
The case I developed this for is glob/dynamic imports where some of the possible imports should not be listed in the client code unless the server instructs the client where to find it. This helps protect unlisted & unreleased posts on my blog, for example.
It could also be useful when a glob could import a very large number of possible modules, such that including the import map would be a performance concern. I'm sure that other people will find cases for it too.
I haven't included documentation here, I'm not quite sure where it would best fit for now. I would also like to add a way to preload dependencies of the import, but as is it's no worse than my existing situation for that. The way I've structured this means it could be put behind a config option pretty easily too, if needed.
Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcsTests
pnpm testand lint the project withpnpm lintandpnpm checkChangesets
pnpm changesetand following the prompts. Changesets that add features should beminorand those that fix bugs should bepatch. Please prefix changeset messages withfeat:,fix:, orchore:.Edits