How to add Preact to existing create-react-app project?

661 Views Asked by At

I have a React project that I'd like to convert to Preact to save on the bundle size.

I followed this recommendation, adding the following elements to my code:

Change the package.json:

 "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },

...and add config-overrides.js:

const { override, addWebpackAlias } = require('customize-cra');

module.exports = override(
  addWebpackAlias({
    'react': 'preact/compat',
    'react-dom': 'preact/compat'
  })
);

Naturally, I also installed preact-compat and preact.

When building my app and viewing the components using the Webpack bundle analyzer, I see that react and react-dom are still in my bundle.

What am I doing wrong with my implementation?

1

There are 1 best solutions below

0
On

react and react-dom showing up is actually correct!

An alias is when you provide something else that it didn't ask for.

Maybe to help describe, imagine you asked me for a certain screwdriver to tighten something, only I know that screwdriver is incorrect, and hand you the correct one instead. You still get the job done, but you don't know any better and refer to that screwdriver as the one you requested. You don't know that I handed you something else entirely.

The aliases here work the same way. CRA ends up asking for React, but we slip it Preact instead. Thanks to preact/compat everything works the same and CRA is none the wiser that we gave it Preact, not React.

You can confirm that the alias works by commenting it out and comparing build sizes. React will be orders of magnitude larger. So if, when uncommented, the build size is much smaller, congrats! The alias works and you're using Preact.