reactjsnext.jscode-splittingstatic-site-generation

Why does Next.js pack JS chunks into static pages?


I'm looking into using Next.js for it's hybrid SSG/SSR features. Why are JS chunks being packed into simple pages that should require ZERO JavaScript?

The build command outputs:

Route (pages)                              Size     First Load JS
┌ ○ /                                      4.9 kB         84.8 kB
├   └ css/ae0e3e027412e072.css             707 B
├   /_app                                  0 B            77.7 kB
├ ○ /404                                   182 B          77.9 kB
├ λ /api/hello                             0 B            77.7 kB
└ ● /posts/firstpost                       341 B          80.2 kB
+ First Load JS shared by all              78 kB
  ├ chunks/framework-7751730b10fa0f74.js   45.5 kB
  ├ chunks/main-e7a7892cb0edc024.js        31 kB
  ├ chunks/pages/_app-1a336683ff51f334.js  497 B
  ├ chunks/webpack-8fa1640cc84ba8fe.js     750 B
  └ css/ab44ce7add5c3d11.css               247 B

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)

Indicating the '404' and 'firstpost' pages are being loaded with unnecessary JS chunks.


Solution

  • Next.js includes runtime packages that handle things like hydration on the client.

    If your page requires no client-side javascript you can add the unstable_runtimeJS flag to the config in your pages file. This is done on a per-page basis.

    // pages/index.js
    export const config = {
      unstable_runtimeJS: false
    }
    
    export default () => <h1>My page</h1>
    
    

    You can read more about this option at https://github.com/vercel/next.js/pull/11949.

    Note: This is an experimental feature, and is undocumented for a reason. Use with caution.