How to reduce the size of electron angular app - javascript

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.

Related

How to create an executable file from React-Electron project

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

TypeError: Cannot read property 'whenReady' of undefined

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.

electron-builder shows white page after compile

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

Electron index.html not loading after building the app

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),

Typescript Electron Renderer process not working

I'm using this boilerplate provided by electron team here. The main process is working but when I use renderer process to create a new window it gives this error
Uncaught TypeError: electron_1.BrowserWindow is not a constructor
at HTMLButtonElement
As I searched it is because of .remote is absent from the compiled typescript to javascript. Code is
main.ts:
import { app, BrowserWindow } from "electron";
import * as path from "path";
let mainWindow: Electron.BrowserWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
height: 600,
width: 800,
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, "../index.html"));
// Open the DevTools.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.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.
mainWindow = 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 OS X 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 OS X 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 (mainWindow === 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.
renderer.ts:
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
import { BrowserWindow } from "electron";
import * as path from "path";
let childWindow: Electron.BrowserWindow;
const newWindowBtn = document.getElementById('new-window');
newWindowBtn.addEventListener('click', (event) => {
const modalPath = path.join('file://', __dirname, '../modal.html');
childWindow = new BrowserWindow({ width: 400, height: 320 });
childWindow.on('close', () => { childWindow = null; });
childWindow.loadURL(modalPath);
childWindow.show();
});
When I tried to not compile the typescript code to javascript & directly run with .remote it works.
So how to do with typescript code?
I was experiencing this same issue.
When installing the quick start with npm and starting it, a folder called "Dist" was created. There is a renderer.js file in this folder. This is where the typescript renderer file is being compiled into JS.
In my index.html, I changed
<script>
require('./src/renderer.ts')
</script>
To <script>
require('./dist/renderer.js')
</script>
And voila! It worked.
I am not sure why, but none of the Electron Typescript Guides are working because of the renderer.ts not being compiled and required on the fly, and there is an open issue on Github (has been there for months) with no response.
Well, this is my workaround. I am not aware of any negative implications this would cause.

Categories