Andrei L
Posted on October 22, 2021
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
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 combining both methods
npm install react@file:node_modules/preact/compat
npm install react-dom@file:node_modules/preact/compat
package.json
changes:
"preact": "^10.5.15",
"react": "file:node_modules/preact/compat",
"react-dom": "file:node_modules/preact/compat",
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!
Cover Photo by Brooke Lark on Unsplash
Posted on October 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.