I have developed one app using angular 6. now I want to make Build Desktop Apps With Electron. I have followed all the steps to make a build. when I run 'npm run electron-build' it makes a build & displays me empty white window it shows nothing. I don't even understand what is the problem.
Thank you in advance.
// main.js
const { app, BrowserWindow } = require('electron')
let win;
function createWindow () {
win = new BrowserWindow({
width: 600,
height: 600,
backgroundColor: '#ffffff',
icon: `file://${__dirname}/dist/assets/logo.png`
})
win.loadURL(`file://${__dirname}/dist/index.html`)
win.on('closed', function () {
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (win === null) {
createWindow()
}
})
// package.json
"name": "demo-electron",
"version": "0.0.0",
"main": "main.js",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"electron": "electron .",
"electron-build": "ng build --prod && electron ."
}
index.html
<base href="./">
I have created a main.js, made changes in the index.html & package.json.
System configuration
OS: Linux x64 (Ubuntu 16),
node 8.11.1
Angular CLI: 6.2.9
Angular: 6.1.10.
Try checking your index.html location in the dist folder and update the win.loadurl path accordingly. Worked for me
use below commands
1) npm install nw --nwjs_build_type=sdk
if above command not worked
2)yarn add --dev nw#0.23.6-sdk-1
Related
I am working on the create-react-app project with typescript. I am trying to use _ (lodash) globally. I followed manuals step by step trying to figure out how to do it, but without any success.
I followed this tutorial https://www.npmjs.com/package/customize-cra. My package.json contains between dependecies:
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"react-app-rewired": "^2.1.8",
"save-dev": "^0.0.1-security"
In devDependencies:
"customize-cra": "^1.0.0"
Based on tutorials I changed also scripts:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",...
My config-overrides.js is located in root folder:
const { addDecoratorsLegacy, override, disableEsLint } = require('customize-cra')
const webpack = require('webpack')
function myOverrides(config) {
if (!config.plugins) {
config.plugins = []
}
config.plugins.push(
new webpack.ProvidePlugin({
_: 'lodash',
}),
)
return config
}
module.exports = override(
addDecoratorsLegacy(),
disableEsLint(),
myOverrides
)
I try to use join(['Hello', 'webpack'], ' ') but failed with error.
TypeScript error in C:/Users/.../webapp/src/index.tsx(27,1): Cannot find name 'join'. TS2304
Does anybody have any idea what should go wrong?
Thank you.
i have problem that i dont know what exactly is the cause the problem is, i have simple code in index.js as main and index.html, in main.js the script will send the version of electron to renderer file index.html, when i'm try it before build that script into .exe, the ipcRenderer can get value from sended value, the following image while i run before build into .exe file like this :
image that run before build into .exe
but when i build it into exe file using electron-packager .
it didn't return any value on it after index.js send version in html file, the following image while the following image while i run after build into .exe file like this
image that run after build into .exe
This is my following script and package.json :
index.js
const { app, BrowserWindow,ipcMain } = require('electron')
function createWindow () {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule : false
}
})
const appVersion = process.env.npm_package_version
// and load the index.html of the app.
win.toggleDevTools()
win.loadFile('index.html')
win.webContents.on('dom-ready', () => {
console.log(`Trying to send app version to renderer: ${appVersion}`)
win.send('app-version', appVersion)
console.log(`Current directory: ${process.cwd()}`);
})
}
app.whenReady().then(createWindow)
index.html
<html>
<head>
<title></title>
</head>
<body>
<div id ="appVersion">
</div>
</body>
</html>
<script>
'use strict'
const { ipcRenderer} = require('electron')
ipcRenderer.on('app-version', function (event,store) {
console.log(store);
});
</script>
package.json
{
"name": "test",
"version": "1.0.0",
"description": "test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^9.2.0",
"electron-packager": "^15.0.0"
}
}
UPDATE: index.js file content added.
I have this electron app that is executing some bash scrips(*.sh) files to perform some task.
Everything is working absolutely fine in the development environment but when building the production build for deb installer for Ubuntu platform, everything is working, like opening on the app, other NodeJS stuff, but bash scripts are not executing.
Problem Statement: How to execute shell scripts in the production build of an electron app for Linux(Ubuntu OS). Getting this error
app/terminal_scripts/timer.sh Not Found
Below are the detailed explanation for the app.
**Project Directory Setup**:
ProjectName
|
app > css | images | js | renders
terminal_scripts
node_modules
package.json
package-lock.json
Where inside the app directory, I have all CSS, images, js, HTML, and terminal scripts.
package.json:
{
"name": "timer",
"productName": "Timely",
"version": "1.0.25",
"description": "This desktop app shows you system clock",
"main": "app/js/main/index.js",
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "nodemon --exec 'electron .'",
"dist": "electron-builder"
},
"homepage": ".",
"keywords": [
"Electron",
"Desktop App"
],
"author": "NotABot Ltd <contact#notabot.com>",
"contributors": [
{
"name": "Not A Bot",
"email": "nab#notabot.com"
}
],
"license": "ISC",
"dependencies": {
"desandro-matches-selector": "^2.0.2",
"electron-context-menu": "^1.0.0",
"electron-is": "^3.0.0",
"fix-path": "^3.0.0",
"isotope-layout": "^3.0.6",
"jquery": "^3.5.0",
"jquery-bridget": "^2.0.1"
},
"build": {
"appId": "com.test.timely",
"productName": "Timely",
"linux": {
"target": "deb",
"category": "System"
}
},
"devDependencies": {
"electron": "^8.1.1",
"electron-builder": "^22.6.0"
}
}
HTML:
<html>
<head>
<title>Timely</title>
</head>
<body>
<button onclick="displayTime()">Display Time</button>
<textarea rows="20" cols="90" id="command-output" disabled="true"></textarea>
<script>
const {app} = require('electron');
function displayTime(){
console.log("button clicked");
let cmd = `bash app/terminal_scripts/timer.sh`;
let completeMessage = 'This is the message';
backgroundProcess(cmd, completeMessage);
}
function getCommandOutput() { return document.getElementById("command-output"); };
function getStatus() { return document.getElementById("status"); };
function appendOutput(msg) { getCommandOutput().value += (msg+'\n'); };
function setStatus(msg) { getStatus().innerHTML = msg; };
function backgroundProcess(cmd, completeMessage){
const process = require('child_process');
var child = process.execFile(cmd, [] , {shell: true} );
appendOutput("Processing......");
child.on('error', function(err) {
appendOutput('stderr: '+err );
});
child.stdout.on('data', function (data) {
appendOutput(data);
});
child.stderr.on('data', function (data) {
appendOutput(data );
});
return new Promise((resolve, reject) => {
child.on('close', function (code) {
console.log(`code is: ${code}`);
if (code == 0){
setStatus(completeMessage);
resolve(1);
}
else{
setStatus('Exited with error code ' + code);
resolve(-1);
}
});
});
}
</script>
</body>
</html>
Bash Script:
#!/bin/bash
timer="$(date)"
echo "$timer"
Permission is set 777 for this shell file
Platform Information:
OS: Ubuntu 18.04.4 LTS
NodeJS: 13.6.0
NPM: 6.14.5
Electron: 8.1.1
Electron Builder: 22.6.0
index.js
const {app, BrowserWindow, Menu, Tray, ipcMain, MenuItem} = require('electron');
const path = require('path');
const contextMenu = require('electron-context-menu');
let splashWindow;
function createMainWindow(){
mainWindow = new BrowserWindow({
minHeight: 700,
minWidth: 800,
webPreferences: {
nodeIntegration: true,
webviewTag: true
},
show: false
});
//For dev only
// mainWindow.webContents.openDevTools();
mainWindow.loadFile('app/renderer/index.html');
mainWindow.maximize();
}
app.on('ready', () =>{
createMainWindow();
});
Another way is to move flies to a new directory outside app directory and call it as extraResources.
Inside that directory you can add all your bash files and for production you can use below method.
let urlPath = path.join(process.resourcesPath, '/extraResources/')
and then use let cmd = `${urlPath}timer.sh`;
I have created a new directory alongside the app directory called the termainal_scripts.
Inside this, I have my bash file timer.sh.
I figured out how to execute shell scripts, in production by using process.resourcesPath inside path.join().
So, let the fixed path be as:
let fixedURL = path.join(process.resourcesPath, '/terminal_scripts/');
Then the command to execute will be:
let cmd = `${fixedURL}timer.sh`
I have developed an app in angular 6. I am trying to make .exe build using electron. When I am making an electron build in the dev environment which is working fine but now I want to release a package for windows I have installed electron packager on my machine trying to make a build for windows. I have installed wine on Linux machine to run the build. It is making the build of the app but when I run .exe file it displays me an empty window. I don't understand what the issue is & why it is displaying me an empty screen.
// main.ts
const { app, BrowserWindow } = require('electron')
const path = require('path');
let win;
function createWindow () {
win = new BrowserWindow({
width: 600,
height: 600,
backgroundColor: '#ffffff'
})
win.maximize()
win.loadURL(`file://${__dirname}/dist/task-reporting-tool/index.html`)
win.on('closed', function () {
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (win === null) {
createWindow()
}
})
// package.json
"main": "main.js",
"description": "task-reporting-tool",
"files": [ "build", "*.js", "public"],
"scripts": {
"electron": "electron .",
"electron-build": "ng build --prod && electron .",
"packager": "electron-packager . WinApp --platform=win32 --arch=all"
}
index.html
<base href="./">
I have created a main.js file. done changes in the index.html file & in package.json.
Using npm run packager to make a build. All the required changes are done build successful but displays an empty screen.
Install npm and then try:
electron-packager . --asar
electron-packager . --all
You could try :
win.loadURL(
url.format({
pathname: path.join(__dirname, "/dist/angular-electron/index.html"),
protocol: "file:",
slashes: true
})
);
I am simply trying to change the root folder name from /app to /src, however, when I do and run npm start I get an error:
fs.js:582
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open '/Users/colinsygiel/liquidtool/liquid-tool-system-ui/lts-admin/app/index.html'
I went into the index.html and changed the corresponding app to src, yet I continue to get the same error.
I think it has something to do with that it is still trying to look for index.html in the /app, when it should be looking in /src.
If it help, here are my package.json scripts:
"scripts": {
"analyze:clean": "rimraf stats.json",
"preanalyze": "npm run analyze:clean",
"analyze": "node ./internals/scripts/analyze.js",
"extract-intl": "babel-node --presets latest,stage-0 -- ./internals/scripts/extract-intl.js",
"npmcheckversion": "node ./internals/scripts/npmcheckversion.js",
"preinstall": "npm run npmcheckversion",
"postinstall": "npm run build:dll",
"prebuild": "npm run build:clean",
"build": "cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress",
"build:clean": "npm run test:clean && rimraf ./build",
"build:dll": "node ./internals/scripts/dependencies.js",
"start": "cross-env NODE_ENV=development node server",
"start:tunnel": "cross-env NODE_ENV=development ENABLE_TUNNEL=true node server",
"start:production": "npm run test && npm run build && npm run start:prod",
"start:prod": "cross-env NODE_ENV=production node server",
"presetup": "npm i chalk shelljs",
"setup": "node ./internals/scripts/setup.js",
"postsetup": "npm run build:dll",
"clean": "shjs ./internals/scripts/clean.js",
"clean:all": "npm run analyze:clean && npm run test:clean && npm run build:clean",
"generate": "plop --plopfile internals/generators/index.js",
"lint": "npm run lint:js",
"lint:eslint": "eslint --ignore-path .gitignore --ignore-pattern internals/scripts",
"lint:js": "npm run lint:eslint -- . ",
"lint:staged": "lint-staged",
"pretest": "npm run test:clean && npm run lint",
"test:clean": "rimraf ./coverage",
"test": "cross-env NODE_ENV=test jest --coverage",
"test:watch": "cross-env NODE_ENV=test jest --watchAll",
"coveralls": "cat ./coverage/lcov.info | coveralls"
},
server.js:
const express = require('express');
const logger = require('./logger');
const argv = require('minimist')(process.argv.slice(2));
const setup = require('./middlewares/frontendMiddleware');
const isDev = process.env.NODE_ENV !== 'production';
const ngrok = (isDev && process.env.ENABLE_TUNNEL) || argv.tunnel ? require('ngrok') : false;
const resolve = require('path').resolve;
const app = express();
// If you need a backend, e.g. an API, add your custom backend-specific middleware here
// app.use('/api', myApi);
// In production we need to pass these values in instead of relying on webpack
setup(app, {
outputPath: resolve(process.cwd(), 'build'),
publicPath: '/',
});
// get the intended host and port number, use localhost and port 3000 if not provided
const customHost = argv.host || process.env.HOST;
const host = customHost || null; // Let http.Server use its default IPv6/4 host
const prettyHost = customHost || 'localhost';
const port = argv.port || process.env.PORT || 3001;
// Start your app.
app.listen(port, host, (err) => {
if (err) {
return logger.error(err.message);
}
// Connect to ngrok in dev mode
if (ngrok) {
ngrok.connect(port, (innerErr, url) => {
if (innerErr) {
return logger.error(innerErr);
}
logger.appStarted(port, prettyHost, url);
});
} else {
logger.appStarted(port, prettyHost);
}
});