Reputation: 1016
I have this nextjs application and lighthouse keeps telling me to remove unused chunks.
…chunks/26c47f1….6971807….js 410.0 KiB 399.8 KiB …chunks/25.91c4046….js 437.6 KiB 392.5 KiB …chunks/30.3fdf525….js
I don't know how they are generated and I don't know how to remove them. I've searched everywhere and can't find a solution.
How do I remove the unused chunks after build?
Upvotes: 8
Views: 24624
Reputation: 6628
You should be careful removing those chunks as it can break your build. Those files are a result of code splitting for performance. They are autogenerated on every build. So you will need to manually delete them on every build, but again, it's not recommended to do so.
Lighthouse only test the page you are currently on so you might not be using those chunks on that page but on another page.
The appropriate question is - How to remove unused code prior to build?
Browser extensions can be injecting code that is read by lighthouse and would be considered unused by your application.
You should run lighthouse in incognito mode to prevent this and to get the most accurate score - but this would not solve all of your unused code issues.
You can do tree shaking with the official Next.js bundle analyzer. This can help identify duplicate libraries and to reduce bundle size and chuck sizes. Tree shaking would help identify issues like the following.
Example that shows how unused code gets included via a 3rd party library
This following would include the whole lodash library
import { throttle } from 'lodash'
The correct way is to only import what you are using i.e.
import throttle from 'lodash/throttle'
Note: some third party libraries export everything and you cannot only use the portion you need. You would have to remove such libraries if you want to completely remove unused code.
The chunks can also be truly unused so you need to find/look for:
import
export
export *
and your not using all of the codeThere are some libraries that can find unused code. But for small projects you can just use linting or perform a manual search.
You can also reduce bundle size by dynamically importing code that gets conditionally used.
Lastly, you can still get a 100% lighthouse score even with the unused chunk files. However, you have a lot of unused code so there is likely duplicated or dead code on your end that is in your project that should be removed.
Upvotes: 19
Reputation: 3806
Provided your builds get generated into dist folder - change your package.json build script with this command
build: "rm -rf dist && next build"
Upvotes: 0