DEV Community

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

Posted on • Originally published at santosnicolas.com

5 2

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

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 🎉

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
rizkimcitra profile image
R. Maulana Citra

I'm using Preact, and my page ain't even loading, Preact was good for my Portfolio Website

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?

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay