Photo by Guillaume Bolduc on Unsplash
You can reduce the bundle size of your Next.js application up to 60% by replacing React with Preact
Introduction
Basic "Hello World" Next.js application ships around 80kB of JavaScript to the client. As for such a small app that does nothing, the bundle size is quite big.
What is Preact
Preact is a small and performant React alternative. Preact components look almost identical to React components although with some differences. By using the preact/compat
package you can completely replace React on production and save a lot of kilobytes.
Install Preact
To use Preact we need to install it first. So copy the following lines
yarn add preact
Configure Webpack
The next step is to configure webpack to use Preact on the production build. Edit next-conf.js
and paste webpack config
webpack: (config, { dev, isServer }) => {
if (!dev && !isServer) {
Object.assign(config.resolve.alias, {
react: 'preact/compat',
'react-dom/test-utils': 'preact/test-utils',
'react-dom': 'preact/compat',
})
}
return config
},
Build app
Now run yarn build
and see the results
Caveats
Remember, before you deploy your app to production, test if everything works fine. Some of the libraries that you added to your application may not be compatible with Preact. If all features work well enjoy a smaller bundle size of your website.
If you are looking for even smaller and faster tools check out Solid.js. It is another React similar library mostly focused on performance. Apps built with Solid.js are significantly smaller than React or even Preact websites.
Sources
Thanks to Lee Robinson for this trick with Preact.
Here you can dive deeper into the Preact library