0

How to Replace React with Preact in WordPress Frontity

Posted in Javascript

While playing around with Frontity (a react framework for WordPress) I noticed the compiled bundle size for the default Mars theme was pretty huge clocking in at an unacceptable 390KB of JavaScript. That’s a lot to download before my site will appear. Below I detail how I knocked over 100KB off that size with no discernible difference in functionality simply by swapping out React with its lightweight drop in replacement Preact.

Extending WebPack

To replace React we need to modify Frontity’s webpack configuration. At the time of writing it’s not documented how to do that however a forum post by SantosGuillamot contains a link to a CodeSandbox showing how to do it.

In your root folder’s package.json add the following dependencies:

1
2
3
4
5
6
"dependencies": {
	...
	"change-config": "./packages/change-config",
	"preact": "^10.5.14",
	"preact-render-to-string": "^5.1.19"
}

Create the following files:

  1. /packages/change-config/package.json
  2. /packages/change-config/frontity.config.js

Here’s the contents of package.json:

1
2
3
4
5
6
7
8
9
10
11
{
  "name": "change-config",
  "version": "1.0.0",
  "description": "Frontity package created using the Frontity CLI.",
  "keywords": [
    "frontity",
    "frontity-theme"
  ],
  "license": "Apache-2.0",
  "dependencies": {}
}

And here is frontity.config.js:

1
2
3
4
5
6
export const webpack = ({ config, mode }) => {
    config.resolve.alias["react"] = "preact/compat";
    config.resolve.alias["react-dom/test-utils"] = "preact/test-utils";
    config.resolve.alias["react-dom"] = "preact/compat";
    config.resolve.alias["react/jsx-runtime"] = "preact/jsx-runtime";
};

Now back in your root folder open frontity.settings.js and set the following at the end of the packages section:

1
2
3
4
5
6
7
8
const settings = {
  ...
  "packages": [
    ...,
    "@frontity/tiny-router",
    "@frontity/html2react",
    "change-config"
  ]

That should be it. Run

1
2
npx frontity build
npx frontity serve

Here are the before and after filesizes:

Before:

Frontity base Mars theme bundle size

After:

Frontity Mars theme bundle size with React replaced with Preact

A saving of 110KB! Not too shabby.