next.js
9118a0b6 - Keep server code out of browser chunks (#76660)

Commit
1 year ago
Keep server code out of browser chunks (#76660) Reduces the main chunk's size for a hello world app ~from 60.2 kB to 51.6 kB~ from 53.5 kB to 45.6 kB (after #76622 got merged). In the past we were a bit sloppy with using modules from `src/server` also in universally used modules (server & browser). This led to code ending up in browser chunks that's only meant for the server, e.g. async local storage modules. We did have already quite a few conditional requires with `typeof window` checks for those modules, but not everywhere. This is fixed in this PR. And shared modules are also moved out of `src/server` into either `src/shared/lib` or `src/client`. A simple smoke test is added to ensure we don't regress here, at least for a simple hello world app. A better verification might be some kind of linter rule though. In addition, we don't remove the `typeof window` SWC optimization for Next.js modules anymore (which is still done for other `node_modules`, see #62051), to ensure that guarded code becomes dead code and is eliminated. Ideally, SWC would take care of the DCE solely by using `typeof window` checks, without needing to manually split modules and dynamically requiring them, which is very tedious and we'd like to avoid. But this is currently not the case. Another option worth exploring is using the ESM modules from `next/dist/esm` in hopes of yielding better DCE results.
Author
Parents
Loading