DEV Community

Cover image for ๐Ÿฅ‘ Put your React on a diet
Andrei Luca
Andrei Luca

Posted on

๐Ÿฅ‘ Put your React on a diet

For a long time I heard people complaining that React & ReactDOM has a huge size, and everyone recommended to use Preact instead.

react & react-dom bundle
https://bundlephobia.com/package/react
https://bundlephobia.com/package/react-dom
preact bundle
https://bundlephobia.com/package/preact

Me personally never had the opportunity to try and migrate a React app to Preact till today.

Chiศ™inฤƒu, capital of Moldova has public transport tracking. And we Open Source enthusiasts made a simple app that shows on a map, live location of desired trolleybuses. Roata Wฤƒy

We are using Create React App and some other React third party libraries.

In docs Preact says you need to alias react and react-dom to preact/compat for everything to work. But here we have a problem, create-react-app does not allow aliases by default, you need to eject or use @craco/craco or react-app-rewired.

Because I didn't wanted to add any more configuration to the project, I started to analyse internals of create-react-app maybe I can find any backdoors. Nothing found.

Then I remembered two ways you can install packages using npm

1. Install package (e.g. my-package) from local directory

npm install ../package-directory
Enter fullscreen mode Exit fullscreen mode

This will add in package.json such a line:

"my-package": "file:../package-directory",
Enter fullscreen mode Exit fullscreen mode

2. Install package under a different name

npm install custom-name@npm:react
Enter fullscreen mode Exit fullscreen mode

This will add in package.json such a line:

"custom-name": "npm:react@^17.0.2",
Enter fullscreen mode Exit fullscreen mode

And I realised that npm: is just the protocol, and we can use other protocols, like file:

And what I did next, was amazing to me ๐Ÿ˜€

Install Preact dependency

npm install preact
Enter fullscreen mode Exit fullscreen mode

Install preact/compat folder under react and react-dom name combining both methods

npm install react@file:node_modules/preact/compat
npm install react-dom@file:node_modules/preact/compat
Enter fullscreen mode Exit fullscreen mode

package.json changes:

"preact": "^10.5.15",
"react": "file:node_modules/preact/compat",
"react-dom": "file:node_modules/preact/compat",
Enter fullscreen mode Exit fullscreen mode

magic shia

And create this script.

npm set-script postinstall "rm -f node_modules/react/src/index.d.ts"
Enter fullscreen mode Exit fullscreen mode

This will remove preact/compat types so TypeScript can consume @types/react instead.

npm run start and Boom ๐Ÿ’ฅ our app is working ๐Ÿš€ and we got rid of almost 34KB from bundle.

There is no need to configure your build system at all. It just works!

Pull Request with changes
Netlify Build Details
Application Preview

That's all for today! Bye!

girl sliding


Cover Photo by Brooke Lark on Unsplash

Top comments (0)