Electron + React with Typescript

Tomas Nilsson
3 min readMay 9, 2021

--

Adding Desktop support for a React app is, at a glance, super easy. You have your already done React app running at port 3000 and all you need is a desktop window to run it in. Electron solves this problem!

Setup a blank React project

If you don’t already have an existing React app, then create the blank React app. After this step is completed, you’ll have a Typescript React app running in developer mode on port 3000.

npx create-react-app my-app --template typescript
cd my-app
npm start

Adding desktop support (Electron)

This is important to understand. In developer mode, you will be running two processes. The React app (on port 3000) and Electron.

Tools

npm install electron
npm install --save-dev electron-is-dev

Package json

Edit package.json and add the following:

"main": "electron/main.ts",

Also add this under the “scripts”:

“electron”: “electron .”

The final result should look something like:

electron/main.ts

Now create a new folder under the root named `electron` and add the `main.ts` file:

:!: At the time of writing (May 2021), Electron does have support for TypeScript but not for ES6 modules (read: import electron from ‘electron’).

const electron = require('electron')
const path = require('path')
const isDev = require('electron-is-dev')
const app = electron.app;
let browserWindow // : BrowserWindow | undefined;
function createWindow() {
browserWindow = new electron.BrowserWindow({ width: 800, height: 600, show: false }); let url = isDev ? "http://localhost:3000" : `file://${path.join(__dirname, '../build/index.html')}`; console.log(`Creating window. Target=${url}`); browserWindow.loadURL(url); browserWindow.once('ready-to-show', () => { if (browserWindow)
browserWindow.show()
else
console.log("Got ready-to-show, but mainwindow is gone. Closed?")
});
browserWindow.on('closed', () => {
browserWindow = undefined;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
app.quit();
});

Test it!

You need to terminal windows for this. Wait for the React Dev server to start first.

# Start the dev server at port 3000 
npm start
# Start the desktop app
npm run electron

Additional information

So a couple of caveats:

React doesn’t support built-in modules such as ‘fs’ and running the app within Electron does not change that! It’s still a React app with all it’s benefits and drawbacks.

If you absolutely need access to (for example) ‘fs’, then this guide isn’t for you :( After some researching I think it can be done by making Electron load the compiled result in “out” / “build”, but you need to figure that out by yourself.

Enjoy

:)

--

--