React/JS Uncaught ReferenceError: require is not defined - javascript

I have just started learning JS/react and I got an error from a html file complaining as "Uncaught ReferenceError: require is not defined". Please see below as an example.
The error is coming from the line 8
const electron = require('electron');
from the following code
this is addWindow.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add shopping list item</title>
</head>
<body>
<script>
const electron = require('electron');
const {ipcRenderer} = electron;
const form = document.querySelector('form');
form.addEventListener('submit', submitForm);
function submitForm(){
e.preventDefault();
}
</script>
<form>
<div>
<label>Enter Item</label>
<input type="text" id="item" autofocus>
</div>
<button type="submit">add item</button>
</form>
</body>
</html>
I have researched and noticed a lot of other people are having the issue so I added
nodeIntegration: true,
this is main.js
const electron = require("electron");
const url = require("url");
const path = require("path");
const { app, BrowserWindow, Menu } = electron;
let mainWindow;
let addWindow;
//listen
app.on("ready", function () {
//create new window
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
},
});
//
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, "mainWindow.html"),
protocol: "file:",
slashes: true,
})
);
//Quit app when closed
mainWindow.on("closed", function () {
app.quit();
});
//build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
//insert menu
Menu.setApplicationMenu(mainMenu);
});
//handle add window
function createAddWindow() {
//create new window
addWindow = new BrowserWindow({
width: 300,
height: 200,
title: "Add shopping list item",
webPreferences: {
nodeIntegration: true,
preload: `${__dirname}/preload.js`,
},
});
//
addWindow.loadURL(
url.format({
pathname: path.join(__dirname, "addWindow.html"),
protocol: "file:",
slashes: true,
})
);
//garbage collection
addWindow.on("close", function () {
addWindow = null;
});
}
//add clear quit
//create menu template
const mainMenuTemplate = [
{
label: "la",
},
{
label: "File",
submenu: [
{
label: "Add Item",
accelerator: process.platform == "darwin" ? "Command+A" : "Ctrl+A", //mac for darwin
click() {
createAddWindow();
},
},
{
label: "Clear Item",
},
{
label: "Quit",
accelerator: process.platform == "darwin" ? "Command+Q" : "Ctrl+Q", //mac for darwin
click() {
app.quit(); //control Q
},
},
],
},
];
if (process.platform == "darwin") {
// mainMenuTemplate.unshift({});
}
// add dev tool item if not in prod
if (process.env.NODE_ENV !== "production") {
mainMenuTemplate.push({
label: "Developer Tools",
submenu: [
{
label: "Toggle DevTools",
accelerator: process.platform == "darwin" ? "Command+I" : "Ctrl+I",
click(item, focusedWindow) {
focusedWindow.toggleDevTools();
},
},
{
role: "reload",
},
],
});
}
But I still have no luck. Could you please help me?
Thank you.

Have you tried this solution ? :
const ipcRenderer = window.require("electron").ipcRenderer;
Original link : https://github.com/electron/electron/issues/7300#issuecomment-671846484

I think your code need to trans-compile first, this is the scripts part of package.json for my node.js project, maybe useful for you:
"scripts": {
"build": "rm -rf dist && babel ./ -d dist --ignore 'node_modules'",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --exec babel-node src/index.js",
"serve": "node ./dist/index.js"
}

Related

Electron require is not defined in renderer process

I'm starting with electron and for some unknown reason I can't use require() function in renderer process.
Uncaught ReferenceError: require is not defined at index.js:1
package.json
{
"name": "my-electron-app",
"version": "0.1.0",
"author": "your name",
"description": "My Electron app",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [],
"license": "ISC",
"devDependencies": {
"electron": "^12.0.2"
}
}
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const ipc = ipcMain;
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntergration: true,
contextIsolation: false,
devTools: true,
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
win.webContents.openDevTools()
ipc.on("closeApp", ()=>{
console.log("clicked on Close btn")
win.close();
})
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body style="background: white;">
<h1>Hello World!</h1>
<p>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</p>
<button id="closeBtn">close</button>
<script defer src="index.js"></script>
</body>
</html>
index.js
const { ipcRenderer } = require('electron');
const ipc = ipcRenderer;
var closeBtn = document.getElementById('closeBtn');
closeBtn.addEventListener("click", ()=>{
ipc.send("closeApp");
});
Screenshot of my program
I am doing everything like in the tutorial, I have searched for solution for two days and tried everything, nothing works. I am worried that only I have that problem :v
There's a typo in nodeIntegration (you spelled it nodeIntergration). That's probably the problem

Bash Scripts Are Not Executing From Production Build of Electron App

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`

vue html-tag not rendering in electron

just trying to set up my first ever electron & vue.js app with webpack and running into the problem that my vue component is not getting rendered.
Here is my project structure
webpack.config.js:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './app/main.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.vue$/,
use: {
loader: 'vue-loader'
}
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}
}
]
},
plugins: [
new webpack.ExternalsPlugin('commonjs', [
'electron'
])
]
}
main.js (electron entry point):
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
let mainWindow;
var createWindow = () => {
mainWindow = new BrowserWindow({width: 800, height: 600});
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
index.html (rendered by electron):
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<app></app>
<script src="dist/bundle.js"></script>
</body>
</html>
app/App.vue (vue root component):
<template>
<div>{{ msg }}</div>
</template>
<script>
export default {
data() {
return {
msg: "root component"
}
}
}
</script>
app/main.js (webpack entry point):
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: 'app',
components: { App }
})
I then run webpack to create the bundle.js which executes without any problems. But when i run npm run start (aka electron main.js) i get a blank screen and when I inspect the code it seems to be missing the app-tag:
resulting electron window
If I change 'el: "app"' to 'el: "body"' the whole body even is missing.
This is my first attempt to deal with this technologies and I have no idea what's wrong - any help?
So I came up with the solution by myself. If in app/main.js I replace
components: { App }
with
render: h => h(App)
it works.
If someone knows why please let me know.

How to use auto-launch to start app on system startup?

package.json:
{
"name": "electronapp",
"version": "1.0.0",
"description": "electron auto-launch",
"main": "index.js",
"scripts": {
"start": "electron .",
"build": "electron-packager . --all"
},
"author": "ivie",
"license": "ISC",
"devDependencies": {
"Q": "^1.0.0",
"asar": "^0.13.0",
"electron": "^1.7.6",
"electron-packager": "^9.1.0",
"electron-prebuilt": "^1.4.13",
"fs-jetpack": "^1.2.0",
"grunt-electron-installer": "^2.1.0",
"rcedit": "^0.9.0"
},
"dependencies": {
"auto-launch": "^5.0.1"
}
}
index.js:
var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var path = require('path');
app.on('ready', ()=>{
var mainwindow = new BrowserWindow({
width: 1200,
height: 800,
icon: "favicon.ico",
frame:true,
title:'Menuboard',
fullscreen: false,
autoHideMenuBar: false
})
mainwindow.openDevTools();
mainwindow.loadURL('https://www.google.com');
mainwindow.on('closed', function() {
mainwindow = null;
});
});
app.on('window-all-closed', function() {
if(process.platform != 'darwin')
app.quit();
})
I have generated an electron .exe using this code. It's getting executed when I'm double clicking on it. But, I want to run it on windows startup. I got to know about auto-launch. But, I'm not sure how to use it in my application? Any help would be appreciated.
Load auto-launch module:
const AutoLaunch = require('auto-launch');
Then add this after app.on('ready', ()=>{:
let autoLaunch = new AutoLaunch({
name: 'Your app name goes here',
path: app.getPath('exe'),
});
autoLaunch.isEnabled().then((isEnabled) => {
if (!isEnabled) autoLaunch.enable();
});
FYI this is now provided by Electron out of the box:
https://electronjs.org/docs/api/app#appsetloginitemsettingssettings-macos-windows
Example:
const electron = require("electron")
electron.app.setLoginItemSettings({
openAtLogin: arg.settings.startOnStartup,
path: electron.app.getPath("exe")
});
EDIT
Based on new comments, this may be out of date. Consider trying Timur Nugmanov's answer first.
At current electron release(19.0.0), the code below works fine:
app.setLoginItemSettings({
openAtLogin: true
})

Electron - running into some issues with start command and window sizing

So I've built a trivial application using Electron.
I can start the app using the command 'electron index.html, but not the command 'electron .', even though this is explicitly declared in the package.json
{
"name": "remind-me",
"version": "1.0.0",
"description": "information management tool",
"main": "index.js",
"scripts": {
"start": "electron ."
},
"repository": {
"type": "git",
"url": "tokumk"
},
"dependencies": {
"electron": "^1.6.11"
}
}
a second issue related to window sizing. my BrowserWindow is always the same size regardless of setting it to something else. Here is an example of my index.js. The setting background color is also completely ignored.
index.html
<html>
<head>
</head>
<body>
<div id="container">
<h3>remind me</h3>
<form>
<input type = text action="post"></input>
<input type="submit" value="send" name="submit">
<form>
</div>
</body>
<script>
require('./renderer.js');
</script>
</html>
index.js
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = ('url');
// window object
let win;
function createWindow(){
// set window size and background color
win = new BrowserWindow({
width: 450,
height: 400,
backgroundColor: '#2e2c29'
});
win.loadURL(url.format({
pathname: path.join(__dir, 'index.html'),
protocol: 'file',
slashes: true
}));
win.webContents.openDevTools();
win.on('closed', ()=> {
win = null;
});
app.on('ready', createWindow);
app.on('window-all-closed', ()=>{
if(process.platform !== 'darwin'){
app.quit();
}
});
}
I think the problem is that you're running the application like electron index.html which just loads index.html in a window and nothing else so if you run electron like: electron index.js I think it would work

Categories