Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 22, 2021 02:28 am GMT

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.

Chiinu, 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 Wy

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 and 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

This will add in package.json such a line:

"my-package": "file:../package-directory",

2. Install package under a different name

npm install custom-name@npm:react

This will add in package.json such a line:

"custom-name": "npm:react@^17.0.2",

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

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

npm install react@file:node_modules/preact/compatnpm install react-dom@file:node_modules/preact/compat

magic shia

And create this script.

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

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


Original Link: https://dev.to/iamandrewluca/put-your-react-on-a-diet-3c6d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To