Skip to content

Instantly share code, notes, and snippets.

@ah-cog
Forked from matthewjberger/notes.md
Last active August 31, 2017 10:48
Show Gist options
  • Save ah-cog/8c49e3fb8eb9356a74b68bb1cefdb83d to your computer and use it in GitHub Desktop.
Save ah-cog/8c49e3fb8eb9356a74b68bb1cefdb83d to your computer and use it in GitHub Desktop.
How to make an electron app using Create-React-App and Electron with Electron-Builder.

Paraphrased from an excellent blog post by Christian Sepulveda

create-react-app my-app
cd my-app
npm install --save-dev electron
npm install -g foreman # for process management
npm install

Add electron-quick-start's main.js to src folder as electron-starter.js.

Make the mainWindow.loadUrl section look like this:

// load the index.html of the app.
const startUrl = process.env.ELECTRON_START_URL || url.format({
    pathname: path.join(__dirname, '/../build/index.html'),
    protocol: 'file:',
    slashes: true
});
mainWindow.loadURL(startUrl);

Create a file called electron-wait-react.js in src directory:

const net = require('net');
const port = process.env.PORT ? (process.env.PORT - 100) : 3000;

process.env.ELECTRON_START_URL = `http://localhost:${port}`;

const client = new net.Socket();

let startedElectron = false;
const tryConnection = () => client.connect({port: port}, () => {
        client.end();
        if(!startedElectron) {
            console.log('starting electron');
            startedElectron = true;
            const exec = require('child_process').exec;
            exec('npm run electron');
        }
    }
);

tryConnection();

client.on('error', (error) => {
    setTimeout(tryConnection, 1000);
});

Make package.json look like this at the bottom:

"homepage": "./",
  "main": "src/electron-starter.js",
  "scripts": {
    "start": "nf start -p 3000",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "electron": "electron .",
    "electron-start": "node src/electron-wait-react",
    "react-start": "react-scripts start"
  }

Add Procfile to root

react: npm run react-start
electron: npm run electron-start

Run using

npm start

TODO:

  • Add Typescript instructions
  • Add electron-builder instructions
  • Add Spectron instructions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment