Search code examples
webpacknext.jslighthouse

How to remove .js chunks in Nextjs application?


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?


Solution

  • 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

    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.


    Tree shaking and 3rd party libraries

    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.


    Your own code

    The chunks can also be truly unused so you need to find/look for:

    • unused import
    • unused export
    • unused variables
    • export * and your not using all of the code
    • code that is in your project folders but not used
    • conditional code that can't ever be reached - these issues are really common - linter will pick these up

    There are some libraries that can find unused code. But for small projects you can just use linting or perform a manual search.


    Dynamic imports

    You can also reduce bundle size by dynamically importing code that gets conditionally used.


    Food for thought

    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.