I have a web app created with React. I want to create the desktop version of that app. To do that, i added electron.js file in the public folder. Inside the electron.js file is the basic electron code that take index.html and turn it to a desktop app that looked like this:
const { app, BrowserWindow } = require('electron')
const path = require("path");
const isDev = require("electron-is-dev");
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadURL(isDev ? "http://localhost:3000" : `file://${path.join(__dirname, "../build/index.html")}`);
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
The app is works and I don't add any electron code to the src folder. How can i get the executable for Windows, Mac, and Linux in my React-Electron code? My machine run on linux
You could use a library called electron-builder.
Install the library with npm install or yarn add then add a new task to package.json to run electron-builder for example to build an app to windows, linux and mac you can run, these can be put in package.json as well so you don't need to type it everytime you want to build. It's also possible to build an app using a programmatic API. You'll find more details in the docs, there are also tutorials and guides.
electron-builder -mwl
Related
i have a problem with electron.
TypeError: Cannot read property 'whenReady' of undefined
i use
node 14.0.1
electron 10.1.2
i run my app
"electron:serve": "vue-cli-service electron:serve",
my background.js
const { app, BrowserWindow } = require('electron')
const { server } = require('feature-server-core')
server.start();
function createWindow () {
// Создаем окно браузера.
const win = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 1280,
minHeight: 800,
closable: true,
center: true,
type: "tool",
titleBarStyle: "hidden",
})
win.menuBarVisible = false;
// и загружаем index.html в приложении.
win.loadURL("google.com")
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
This is the problem related to directly calling the 'index.js' with node like node index.js.
You need to use electron index.js or electron .(if your file is index.js)
electron is building your app.
i solved the same problem just typing in the folder's terminal
npm start
You can use npm start instead of node . to execute your application. If you are using an IDE you have to configure npm with the start option.
I had the same symptom but the underlying problem was completely different from what you find elsewhere on the Internet. Normally, this issue comes from accidentally running main.js with node instead of electron. But in my case the problem was that the NTFS case sensitivity flag was set on the project folder and some subfolders because they were initially created using WSL. This lead to weird things like electron.cmd not being found due to Windows looking for electron.CMD with upper-case extension, etc., and apparently also some similar problem inside Electron itself which made it think we are not inside Electron after all, giving us the non-Electron version of electron which has no app.
The solution was to create a copy of the whole project folder using Windows Explorer, and using that one instead of the original folder. Windows Explorer doesn't preserve the case sensitivity flag, thus creating a copy of the folder clears the flag in all subfolders too. (You can then just delete the old folder.)
More information about case sensitivity in NTFS: https://www.howtogeek.com/354220/how-to-enable-case-sensitive-folders-on-windows-10/
Another cause could be having the environment variable ELECTRON_RUN_AS_NODE=1 set, maybe from some experiment or test a long time ago. Make sure this variable isn't set.
I am trying to design an angular app for windows and Linux platforms. I am using the electron framework. I just built a simple app that displays the angular home page. The size of this app is around 250MB. This is too large. If anyone has developed an electron-angular app. Can you mention the size of your app. And any tips on how to reduce the size of the application.
Note: Angular app is compiled to /dist, its size is just 250KB but when the whole app is built is 250MB!
** main.js**
const { app, BrowserWindow } = require('electron')
let win;
console.log(__dirname);
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 600,
height: 600,
backgroundColor: '#ffffff',
icon: `file://${__dirname}/dist/Angular-electron/favicon.ico`
})
win.loadURL(`file://${__dirname}/dist//Angular-electron/index.html`)
//// uncomment below to open the DevTools.
// win.webContents.openDevTools()
// Event when the window is closed.
win.on('closed', function () {
win = null
})
}
// Create window on electron intialization
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS specific close process
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// macOS specific close process
if (win === null) {
createWindow()
}
})
Below is the root component.
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular-electron';
}
This is the package.json script, I build the angular and simultaneously build electron as shown below
Note: I use the electron-packager to build the app for production.
"builderForWindows": "ng build --prod && electron-packager ./dist --out winx64 --overwrite --platform win32 "
Below is the screenshot of the application.
When you build your app for Electron, it adds all your dependencies in dependencies section of package.json
Try to move all your angular dependencies in devDependencies section of package.json
This should reduce the size of your final package.
Otherwise you should have a look at electron-builder and start building your app as a Linux/MacOS/Windows package.
For example, my electron-angular project generate a 45Mo Windows executable.
I trying to build an Electron app. For that I'm using the following respos:
https://github.com/electron/electron-quick-start
https://github.com/electron-userland/electron-builder
In devoplement mode (electron .) everything works fine. But when I build the app and starting it, it just shows me a blank page without any errors in the dev console or build log.
Why doesn't it work in production? All my files are in one direction:
index.html
main.js
renderer.js
package.json
I didn't changed much in the base main.js file:
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
webSecurity: false
}
})
// and load the index.html of the app.
//mainWindow.loadFile('index.html')
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
// Open the DevTools.
mainWindow.webContents.openDevTools();
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
That's because your output html in production should be located elsewhere, btw I'm using angular with electron and the output is in the dist folder, but I don't use url.format: try with mainWindow.loadURL(`file://$_dirname/index.html`)
or if you have a dist folder mainWindow.loadURL(`file://$_dirname/dist/index.html')
Try changing also
app.whenReady() by app.on("ready",createWindow)
Hope it works afterwards
I have an electron app that works perfectly fine before bundling it with electron-builder. After bundling it and opening the app, I get the following error :
Not allowed to load local resource: file:///tmp/.mount_displa4VwuQh/resources/app.asar/file:/tmp/.mount_displa4VwuQh/resources/app.asar/build/index.html
In the build folder I have the electron.js file and index.html and since the app is starting electron.js and thus index.html got bundled correctly.
Here is my electron.js app entry point(basically boilerplate):
const { app, BrowserWindow } = require('electron')
const url = require('url')
const path = require('path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, './index.html'),
protocol: 'file:',
slashes: true
}));
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
When trying with loadFile() instead of loadUrl() I get the same error, but with this path instead : file:///tmp/.mount_displa4VwuQh/resources/app.asar/index.html
Any idea what is wrong? Thanks in advance!
So it looks like my problem was caused from improper packaging after all. Adding this in package.json "build" configuration fixed it:
"directories": {
"buildResources": "build",
"app": "build"
}
check once your directory path for index.html
I think you follow any tutorial and do not verify your path just once check I hope this will resolve your issue.
pathname: path.join(__dirname, ./src/index.html),
So I have an electron app named main.js which I start with npm start. I've set the start script in package.json to electron main.js and have also tried electron .. When running npm start, everything starts without any errors but the electron window only shows a snapshot of what was on the screen when I started it. I've tried refreshing it but nothing seems to work. Here is how it looks:
Image
It should view localhost:3001 but it doesn't. I've also tried to run electron . directly in the terminal but that gives me electron: command not found. When running ./node_modules/electron/dist/electron . it starts as it should but the same problem occurs. Here is main.js:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const core = require('./app');
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { webSecurity: false },
nodeIntegration: false,
})
mainWindow.loadURL('http://localhost:3001');
// mainWindow.setFullScreen(true)
// mainWindow.setMenu(null);
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})
console.log('Electron window ready')
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
app.quit()
})
core.start()
It seems you didn't install Electron globally, for that you need to run npm install -g Electron
Replace mainWindow.loadURL('http://localhost:3001'); With:
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file:",
slashes: true
})
);
You have not shared your package.json file, but I will guess you did not run npm install --save electron in your terminal.
Also, instead of:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
you want to write it like so:
const electron = require('electron');
const { app, BrowserWindow } = electron;
I would review ES6 destructuring and unless you did not share the code with us, you should start your electron project by assuring that the app object is ready and loading your file like so:
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}/main.html`);
});
You will notice I declared an empty mainWindow variable to take care of any scoping issues you may have as you may have to use mainWindow in other functions as well.