Good afternoon, I am unable to import the electron module in my ts. I have the following error: Cannot find module 'electron'.
My structure:
Project
covarage
dist
electron
main.js
package.json
src
app
components...
assest
environmentes
services
services
index.html
main.ts
polyfills.ts
tsconfig.json
typings.d.ts
angular-cli.json
karma.conf.js
package.json
protractor.conf.js
tslint.json
main.js electron:
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(`file://${__dirname}/index.html`)
mainWindow.webContents.openDevTools()
mainWindow.setMenu(null);
mainWindow.on('closed', function () {
mainWindow = null;
})
}
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
});
const ipc = require('electron').ipcMain
ipc.on('get-app-path', function (event) {
event.sender.send('got-app-path', app.getAppPath())
})
My index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>X</title>
<script>
window.$ = window.jQuery = require('jquery');
var electron = require('electron');
document.write('<base href="' + document.location + '" />');
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body style="padding-top: 70px;">
<app-root>
loading...
</app-root>
</body>
</html>
My import in component:
import { ipcRenderer } from 'electron';
I have tested:
typings.d.ts:
declare var System: any;
declare var electron: any;
declared in script index.html:
var electron = require('electron');
and component:
electron.ipcRenderer.on('got-app-path', function (event, path) {
...
});
nothing happens...
Any suggestion? grateful!
My problem was solved by declaring:
<script>
var electron = require('electron');
</script>
in index.html and typings.d.ts:
declare var electron: any;
My Component:
const {ipcRenderer} = electron;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping'));
Part of the problem was the async!
Related
It is my first time using electron and I faced this error while creating a quit button.
I went thru like 50 threads and most of them said use require('#electron/remote/main').initialize()
and it did not work
electron version :20.1.1
should I downgrade electron to work?
or should I reinstall electron?
or maybe create a new project?
Uncaught TypeError: Cannot read properties of undefined (reading 'getCurrentWindow')
at document.getElementById.onclick (render.js:6:25)
my index.js file:
const { app, BrowserWindow } = require('electron');
const path = require('path');
require('#electron/remote/main').initialize();
if (require('electron-squirrel-startup')) {
app.quit();
}
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
enableRemoteModule: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
webPreferences: true,
preload: path.join(__dirname, 'preload.js'),
},
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
render.js
const { remote } = require('#electron/remote')
document.getElementById('close').onclick = function() {
console.log("debug")
var window = remote.getCurrentWindow();
window.close();
}
and html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Instapath</title>
<link rel="stylesheet" href="index.css" />
<script defer src="render.js"></script>
</head>
<body class="content">
<button id="close" style="position:fixed;">Close</button>
<div><h1>Hi!</h1></div>
</body>
</html>
I am trying to set up an electron app where i send a message to the server, and the server puts the value on the readonly textarea.
But, when i start the app, i see this in the devtoools console:
Uncaught ReferenceError: Cannot access 'socket' before initialization
But, when i open my browser (outside the electron app), it works as i wanted
why my code works as planned on my browser, but not on my electron?
//SERVER HOSTING SECTION
const express = require('express')
const http = require('http')
const socketIo = require('socket.io')
const serverapp = express()
const server = http.createServer(serverapp)
let mensagem
serverapp.use(express.static(__dirname+'/data'))
const io = socketIo.listen(server);
server.listen(8889, ()=>console.log("adm online na porta http://localhost:7000"))
serverapp.get("/",function(req,res){
res.sendFile(path.resolve("index.html"));
})
io.on('connection', (socket) => {
console.log("nova conexao")
socket.on('mensagem',(mensagem)=>{
console.log("mensagem aqui:", mensagem)
io.emit('resposta',mensagem)
})
});
//ELECTRON APP SECTION
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('data/index.html')
//mainWindow.loadURL("http://localhost:7000/index.html");
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
/*
$.getScript("server.js",function(){
console.log("a")
})
*/
// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="estilo.css">
<script src="socket.io/socket.io.js"></script>
<title>Hello World!</title>
</head>
<body>
<h1>aaaaaaaaaa</h1>
<div>
<input type="text" id="textbox" value="aba">
<button onclick ="adicionar()"type="button" id="botao" for="textbox">Enviar</button>
<button onclick ="enviar()"type="button" id="botao2" >Teste</button>
</div>
<textarea name="" id="textarea" cols="30" rows="10" readonly></textarea>
<script src="codigo.js"></script>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
// code that sends and receives the message
let botaoAdicionar=document.querySelector("#botao")
let textbox = document.querySelector('#textbox')
let textarea = document.querySelector("#textarea")
let valortextbox;
console.log(valortextbox)
const socket = io.connect()
function adicionar(){
event.preventDefault();
console.log(textbox.value)
textarea.value+=textbox.value
};
socket.on('resposta',(mensagem)=>{
textarea.textContent+=mensagem
console.log('resposta recebida')
})
function enviar(){
let valortextbox= textbox.value
socket.emit('mensagem', valortextbox)
console.log("a")
}
/*
let testbtn=document.querySelector("#botao2")
testbtn.addEventListener("click", function(){
console.log("a")
})
*/
Problem solved, i just needed to add "nodeIntegration: true" on browser window
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: path.join(__dirname, 'preload.js')
}
})
I've already configured nodeIntegration, contextIsolation and enableRemoteModule in main.js. But the following message still appears:
This error only happens when I try to import the lib.js file through the script.js.
Uncaught Error: Cannot find module './lib'
Require stack:
- C:\Users\sergi\Documents\Desenvolvimento\phoras\electron-quick-start\app\index.html
at Module._resolveFilename (internal/modules/cjs/loader.js:887)
at Function.o._resolveFilename (electron/js2c/renderer_init.js:33)
at Module._load (internal/modules/cjs/loader.js:732)
at Function.f._load (electron/js2c/asar_bundle.js:5)
at Function.o._load (electron/js2c/renderer_init.js:33)
at Module.require (internal/modules/cjs/loader.js:959)
at require (internal/modules/cjs/helpers.js:88)
at script.js:1
I am using the following version:
Electron: v12.0.2
NodeJS: v12.5.0
NPM: v6.9.0
I'm using electron from that repository: repository
Below are the files that I am using
app/index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
</head>
<body>
<script type="module" src="./js/script.js"></script>
</body>
</html>
app/js/script.js
const {lib} = require('./lib'); // this is where the error is happening
lib.message('hello');
app/js/lib.js
function message(msg) {
console.log(msg);
}
main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
}
})
mainWindow.loadFile('app/index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
What can I do to fix this error when trying to import lib.js?
Try this lib method
export function square(x) { return x * x; }
call that way ---
import { square} from 'lib';
console.log(square(11));
----- OR ------
import * as lib from 'lib';
console.log(lib.square(11));
must read Module systems for JavaScript
How to integrate 3 c++ libraries(fftw3, libsnd, zita resampler) into a simple electron app .......
I have created a simple Hello world App in Electron, further I'm looking for ways to integrate c++ libraries into this Helloworld app....
I would be thankful for Any help extended towards this.
below is the main.js code
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
this is the index.html code
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset = "UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
I'm writing my first electron app, and I was trying to show a window when a button is clicked. I have an error message:
Uncaught ReferenceError:
require is not defined
at dialog.js:2
I'm using the version "electron-nightly": "^6.0.0-nightly.20190213"
here is the code:
index.js:
const electron = require('electron');
const {app, BrowserWindow} = electron;
const path = require('path');
const url = require('url');
let win
function main(){
win = new BrowserWindow({ width: 500, height: 400});
win.loadURL(url.format( {
pathname: path.join(__dirname, './index.html'),
protocol: 'file',
slashes: true
} ));
win.webContents.openDevTools()
}
exports.openDialog = () => {
let dial = new BrowserWindow({ width: 400, height: 200});
dial.loadURL(url.format( {
pathname: path.join(__dirname, './dialog.html'),
protocol: 'file',
slashes: true
} ));
}
app.on('ready', main);
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello world</title>
</head>
<body>
<h1>Hello Electron!!</h1>
<button id="btn">Show dialog</button>
<script src="./dialog.js"></script>
</body>
</html>
dialog.js:
const index = require('electron').remote.require('./index.js'); //Error line: Uncaught ReferenceError: require is not defined at dialog.js:2
const button = document.getElementById('btn');
button.addEventListener('click', () => {
index.openDialog();
});
Is this error something about ES6+?
You may have to enable Node integration in your new window (disabled by default according to the documentation) :
index.js
function main() {
win = new BrowserWindow({
width: 500,
height: 400,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile("index.html") // To load local HTML files easily
}