The following guide has been tested with React 18, Babel 7, and Webpack 5.
To integrate React into an Electron Forge project, follow these steps:
Create Your Electron App with Electron Forge:
Scaffold a new app using the following command:npm init electron-app@latest my-new-app -- --template=webpack
You should use the
webpack-typescript
template instead if you are using TypeScript in your project.Add React Dependencies:
Install the necessary packages to yourdevDependencies
so that JSX and other React features can be used properly:npm install --save-dev @babel/core @babel/preset-react babel-loader
Configure Webpack:
Set up thebabel-loader
module with the React preset in yourwebpack.rules.js
file1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// webpack.rules.js
module.exports = [
// ... existing loader config ...
{
test: /\.jsx?$/,
use: {
loader: "babel-loader",
options: {
exclude: /node_modules/,
presets: ["@babel/preset-react"],
},
},
},
// ... existing loader config ...
];Add Basic React Packages:
Install the following React packages to yourdependencies
:npm install --save react react-dom
Integrate React Code:
You can now start writing and using React components in your Electron app.
Here’s a minimal example of how to add React code:1
2
3
4
5// src/app.jsx
import React from "react";
import { createRoot } from "react-dom/client";
const root = createRoot(document.body);
root.render(<h2>Hello from React!</h2>);1
2
3// src/renderer.js
// Import your React components here if needed
import "./app";Add JSX support in TypeScript
If you prefer to use TypeScript over JavaScript, then you need to enable JSX support in thetsconfig.json
file:1
2
3
4
5
6
7{
"compilerOptions": {
"jsx": "react"
// ....
}
// ...
}