'How to convert create-react-app to Preact?

As per Preact documentation, to convert a React app to Preact you have to alias webpack:

{
  "resolve": {
    "alias": {
      "react": "preact-compat",
      "react-dom": "preact-compat"
    }
  }
}

How can you do this with create-react-app since that hides webpack under react-scripts dependency?

Thank you!



Solution 1:[1]

I think the most elegant solution is to use customize-cra. This way you can avoid ejecting or maintaining a separate fork of create-react-app.

  • First, you need to install customize-cra:
yarn add customize-cra react-app-rewired --D
  • Then, go to package.json, change your scripts to the following (this step is crucial but is not explicitly mentioned in customize-cra's docs):
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  • Go to the root of your project, create a file called config-overrides.js with the following content (assuming you're using Preact X):
const { override, addWebpackAlias } = require('customize-cra');

module.exports = override(
  addWebpackAlias({
    'react': 'preact/compat',
    'react-dom': 'preact/compat'
  })
);
  • Run yarn start... And Voila!

Solution 2:[2]

Alternatively, you can get it working with craco:

// craco.config.js
module.exports = {
  webpack: {
    alias: {
      "react": "preact/compat",
      "react-dom": "preact/compat"
    }
  }
}

Note: Do not uninstall react, @types/react, or @types/react-dom after adding preact!

react is still required by react-scripts to run craco start and friends.

@types/* are still required by your IDE for type suggestions.

Note: Bundle analyzers may still report that you're using React!

Make sure to double-check your output directory for real build sizes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huy
Solution 2 serg06