Reduce Unused JavaScript Nextjs Bundle Analysis

4th Nov 2021

Reduce Unused JavaScript Nextjs Bundle Analysis

The Lighthouse report says that the page is only using 1/3 of the JavaScript within the main _app file. Before I start making assumptions about what components or features need to be lazy loaded from the main app I need to do some analysis on the bundle.

Let's remind ourselves of the previous report after I removed Youtube.

Report after I Removed Youtube
Report after I Removed Youtube

Webpack had a bundle analyzer which I have used many times to inspect what has been compiled into one of the JavaScript files. After a quick search I found that there is a NextJs plugin which integrates it into next build. The plugin is @next/bundle-analyzer and I configured it within next.config.js.

Adding bundle analyzer
Adding bundle analyzer

After adding a new script to my package.json ANALYZE=true next build I am able to look at what code is inside the _app chunk.

I can quite clearly see that a large proportion of the code bloat is down to the way I have integrated TinaCMS. I use Tina to edit this website (and it's great). I expect that we don't need most of the @tinacms scope or the codemirror dependency in the main _app bundle.

_app chunk analysis
_app chunk analysis

Looking at my pages/_app.tsx file it looks like I need to convert some imports so that they only load the chunk if the page is in an editing mode.

import { TinaCMS, TinaProvider } from 'tinacms'
import { MarkdownFieldPlugin } from 'react-tinacms-editor'
import { TinacmsGithubProvider } from 'react-tinacms-github'
import { NextGithubMediaStore } from 'next-tinacms-github'
import { BrowserStorageClient } from '@tinacms/browser-storage'

I will look at the best way to do this next.

Lighthouse Scores Series