Giter VIP home page Giter VIP logo

react-typescript-electron-sample-with-create-react-app-and-electron-builder's Introduction

React-TypeScript-Electron sample with Create React App and Electron Builder

This project was bootstrapped with Create React App with --template typescriptoption.

On the top of it, the following features have been added with relatively small changes:

  • TypeScript supports for Electron main process source code
  • Hot-reload support for Electron app
  • Electron Builder support

Available Scripts in addition to the existing ones

npm run electron:dev

Runs the Electron app in the development mode.

The Electron app will reload if you make edits in the electron directory.
You will also see any lint errors in the console.

npm run electron:build

Builds the Electron app package for production to the dist folder.

Your Electron app is ready to be distributed!

Project directory structure

my-app/
├── package.json
│
## render process
├── tsconfig.json
├── public/
├── src/
│
## main process
├── electron/
│   ├── main.ts
│   └── tsconfig.json
│
## build output
├── build/
│   ├── index.html
│   ├── static/
│   │   ├── css/
│   │   └── js/
│   │
│   └── electron/
│      └── main.js
│
## distribution packages
└── dist/
    ├── mac/
    │   └── my-app.app
    └── my-app-0.1.0.dmg

Do it yourself from scratch

Generate a React project and install npm dependencies

npx create-react-app my-app --template typescript
cd my-app
yarn add @types/electron-devtools-installer electron-devtools-installer electron-is-dev electron-reload
yarn add -D concurrently electron electron-builder wait-on cross-env

Make Electron main process source file

electron/tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "strict": true,
    "outDir": "../build", // Output transpiled files to build/electron/
    "rootDir": "../",
    "noEmitOnError": true,
    "typeRoots": [
      "node_modules/@types"
    ]
  }
}

electron/main.ts

import { app, BrowserWindow } from 'electron';
import * as path from 'path';
import * as isDev from 'electron-is-dev';
import installExtension, { REACT_DEVELOPER_TOOLS } from "electron-devtools-installer";

let win: BrowserWindow | null = null;

function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  if (isDev) {
    win.loadURL('http://localhost:3000/index.html');
  } else {
    // 'build/index.html'
    win.loadURL(`file://${__dirname}/../index.html`);
  }

  win.on('closed', () => win = null);

  // Hot Reloading
  if (isDev) {
    // 'node_modules/.bin/electronPath'
    require('electron-reload')(__dirname, {
      electron: path.join(__dirname, '..', '..', 'node_modules', '.bin', 'electron'),
      forceHardReset: true,
      hardResetMethod: 'exit'
    });
  }

  // DevTools
  installExtension(REACT_DEVELOPER_TOOLS)
    .then((name) => console.log(`Added Extension:  ${name}`))
    .catch((err) => console.log('An error occurred: ', err));

  if (isDev) {
    win.webContents.openDevTools();
  }
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
});

Adjust package.json

Add properties for Electron

  "homepage": ".", # see https://create-react-app.dev/docs/deployment#serving-the-same-build-from-different-paths
  "main": "build/electron/main.js",

Add properties for Electron Builder

  "author": "Your Name",
  "description": "React-TypeScript-Electron sample with Create React App and Electron Builder",
  ...
  "build": {
    "extends": null, # see https://github.com/electron-userland/electron-builder/issues/2030#issuecomment-386720420
    "files": [
      "build/**/*"
    ],
    "directories": {
      "buildResources": "assets" # change the resource directory from 'build' to 'assets'
    }
  },

Add scripts

  "scripts": {
    "postinstall": "electron-builder install-app-deps",
    "electron:dev": "concurrently \"cross-env BROWSER=none yarn start\" \"wait-on http://127.0.0.1:3000 && tsc -p electron -w\" \"wait-on http://127.0.0.1:3000 && tsc -p electron && electron .\"",
    "electron:build": "yarn build && tsc -p electron && electron-builder",

Many thanks to the following articles!

react-typescript-electron-sample-with-create-react-app-and-electron-builder's People

Contributors

dependabot[bot] avatar ledenmat avatar macil avatar pvinis avatar ru4ert avatar yhirose avatar zefaxet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-typescript-electron-sample-with-create-react-app-and-electron-builder's Issues

preload issue

in the mian.ts

function createWindow() {
	win = new BrowserWindow({
               ...
		webPreferences: {
			nodeIntegration: true,
			webviewTag: true,
			enableRemoteModule: true,
			contextIsolation: true,
			plugins: true,
			webSecurity: false,
			autoplayPolicy: 'no-user-gesture-required',
			preload: path.join(__dirname, './preload.js'),
			// preload: process.cwd() + path.join(__dirname, './preload.ts'),
		},
	})

// preload.ts
console.log('electron preload')
window.ipc = ipc
window.hello = 'hello'
`
image

code executed but not work

webview preload also not work

<webview
		src="http://localhost:8888/dist/webview.html"
		style={{ width: '600px', height: '600px' }}
		// preload={`${path.join(__dirname, '/../../electron/preload.js')}`}
		preload={`file://${path.join(__dirname, '../../electron/preload.js')}`}
	/>

​ case 1: not start with ' file '
​ error : Only "file:" protocol is supported in "preload" attribute.

case 2: with ' file ':

webview deveTools :
image

thanks

`'BROWSER' is not recognized as an internal or external command`

The original scripts will get warning in powershell and exit code 1.

I found a solution maybe to fix this problem:

Use the following config

"scripts": {
  "electron:dev": "concurrently \"cross-env BROWSER=none yarn start\" \"wait-on http://localhost:3000 && tsc -p electron -w\" \"wait-on http://localhost:3000 && tsc -p electron && electron .\"",
},
"devDependencies": {
  "cross-env": "^7.0.3"
}

instead of

"scripts": {
  "electron:dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && tsc -p electron -w\" \"wait-on http://localhost:3000 && tsc -p electron && electron .\"",
}

in package.json

Issue with electron:dev script.

Hi. Thanks for putting together this project bootstrapper. It's really nice and saving me time.
I am having an issue when trying to run
yarn run electron:dev

This is the result:
image

λ yarn run electron:dev
yarn run v1.21.1
$ concurrently "BROWSER=none yarn start" "wait-on http://localhost:3000 && tsc -p electron -w" "wait-on http://localhost:3000 && tsc -p electron && electron ."
[0] 'BROWSER' is not recognized as an internal or external command,
[0] operable program or batch file.
[0] BROWSER=none yarn start exited with code 1

This is apparently referring to the BROWSER=none line, witch is not valid batch script. I would bet that this wasn't designed to be run on Windows, or at the very least not outside of shell script.

This is on Windows 10 through ConEmu batch.
Does this look familiar to you? I have a feeling that this is a Windows-specific problem. Do you know of a work-around for my use case?

build for apple m1

how can i build for apple m1?
yarn electron:build produces x64 binary

isDev is always true

electron-is-dev's isDev variable is always true.

The problem seems to be in the way isDev is imported.

Instead of

import * as isDev from "electron-is-dev";

Using the following will solve the issue:

import isDev from "electron-is-dev";

Missing npx cmd into README.md file

it's not create-react-app my-app --template typescript, it's npx create-react-app my-app --template typescript.
Should I fork it and make a pull request?

error occurs after hot reload

When I modify something, the hot reload works. But there're errors in development tools.

Uncaught ReferenceError: process is not defined
at Object.4043 (:2:13168)
at r (:2:306599)
at Object.8048 (:2:9496)
at r (:2:306599)
at Object.8641 (:2:1379)
at r (:2:306599)
at :2:315627
at :2:324225
at :2:324229
at HTMLIFrameElement.e.onload (index.js:1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.