Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Explanation] vite-plugin-ssr automagically loads the files living at dist/server/ #403

Closed
brillout opened this issue Aug 3, 2022 · 0 comments

Comments

@brillout
Copy link
Member

brillout commented Aug 3, 2022

⚠️ This is for expert users.

If the only thing you want is to solve your problem, then skip reading this text and instead check out vite-plugin-ssr.com/importBuild.cjs.

If you are curious how vite-plugin-ssr automagically imports files living at dist/server/, then read on.

Normally importing dist/server/importBuild.cjs as described in vite-plugin-ssr.com/importBuild.cjs should fix your situation and there is nothing more for you to know.

But, if you curious, this is what is going.

Trick 1

Trick 1: vite-plugin-ssr uses a little Vite plugin vite-plugin-import-build that automatically generates a file that imports dist/server/importBuild.cjs on our behalf:

// node_modules/vite-plugin-import-build/dist/autoImporter.js

exports.status = 'SET';
exports.load = () => { require('../../../dist/server/importBuild.cjs') };

This trick doesn't work:

  • If we install npm packages after running $ vite build, then autoImporter.js is erased.

    (Because vite-plugin-import-build generates node_modules/vite-plugin-import-build/dist/autoImporter.js at build-time when we run $ vite build. So, if we $ rm -r node_modules/ && npm install, then the link living at node_modules/vite-plugin-import-build/dist/autoImporter.js is erased.)

  • When using Yarn PnP which installs dependencies in an immutable way.

    (Because this means that vite-plugin-import-build cannot generate node_modules/vite-plugin-import-build/dist/autoImporter.js.)

In theses situations, vite-plugin-ssr uses a second trick.

Trick 2

Trick 2: vite-plugin-ssr dynamically searches for dist/server/importBuild.cjs and loads it.

But that doesn't work:

Fallback

If both tricks don't work, then we fallback to manually import dist/server/importBuild.cjs as described in vite-plugin-ssr.com/importBuild.cjs.

We need the fallback only if both trick 1 and trick 2 don't work which, all-in-all, is a rare situation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant