DEV Community

loading...
Cover image for Preact: Optimize your Next.js build with 5 lines of code

Preact: Optimize your Next.js build with 5 lines of code

Nicolas Santos
I'm a software engineer based in Montevideo, UY specializing in building exceptional websites, applications, and everything in between
Originally published at santosnicolas.com ・1 min read

Hey hey👋 let's get started on this quickly, in this note you can find a way to optimize your build size by 38% with just a lib install and 5 lines of code.

What is Preact?

According to his website, Preact is a Fast 3kB alternative to React with the same modern API. Basically overrides a lot of the methods that use React, like render for example, and optimize it at build-time.

Optimize Next.js build with Preact

  1. Install Preact
    yarn add preact or npm i preact

  2. Create a next.config.js if you don't already have one in the root of your project
    touch next.config.js

  3. Add the next code or adapt your previous config

   module.exports = {
     webpack(config, { dev, isServer }) {
       // ${previousConfig...}

       // Replace React with Preact only in client production build
       if (!dev && !isServer) {
         Object.assign(config.resolve.alias, {
           react: "preact/compat",
           "react-dom/test-utils": "preact/test-utils",
           "react-dom": "preact/compat",
         })
       }

       return config
     },
   }
Enter fullscreen mode Exit fullscreen mode

Ready 🎉

Discussion (1)

Collapse
ferluisxd profile image
Luis Vilca

Question, if we add preact/compat then we lose the whole purpose of preact and it's 3kb size. Is this really the solution?