Closed SlimDaddy228 closed 1 month ago
It turned out that this is not a problem with the configuration of webpack5, which uses Next, but a feature of how tree shaking works in webpack5
If anyone is interested, I found an article that very clearly explains how it works, I advise you to read it
https://blog.theodo.com/2021/04/library-tree-shaking/
The solution that helped me is to split all exports into separate files, make an index file that exports from these files
As a result, I split the files that contained a lot of export const, export .. and so on, and made them into separate files for each constant, function, whatever.
Thanks to the modular approach using the index barrel file, I was able to achieve results of almost 3 times, and continue to improve these values further
You also need to include in packages.json
- sideEffects: false
1.
Result:
This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.
Link to the code that reproduces this issue
https://github.com/SlimDaddy228/nextjs-bug-report
To Reproduce
npm run build
Current vs. Expected behavior
We can observe that on completely different pages, completely different const imports are used, but the only thing they have in common is that they are in the same file
app/test/layout.tsx
app/layout.tsx
After building the project, we can see this result
.next/static/chunks/app/layout-8c27ef9d132a8703.js
app/.next/static/chunks/app/test/layout-276ac73023152d33.js
Instead of separating the imported constants, it combines them into one single whole on all pages, and because of this the bundle unnecessarily increases
What behavior was expected:
.next/static/chunks/app/layout-8c27ef9d132a8703.js
Should only have TEST_2 constantapp/.next/static/chunks/app/test/layout-276ac73023152d33.js
Should only have TEST constantYou can add one more page, one more constant to this file in which the constants are exported, and it will add all 3 constants to all 3 pages
Provide environment information
Which area(s) are affected? (Select all that apply)
Developer Experience, Instrumentation, Pages Router, TypeScript, SWC, Webpack
Which stage(s) are affected? (Select all that apply)
next build (local)
Additional context
This bug works from version 12 of nextjs (the maximum from which I tested) to v.14
It doesn’t matter app router or pages router, it works everywhere