I am trying to use electron with latest Vite 2/Vue 3. I have setup two versions of electron's main file so I can test and work with both dev server and the build:
dev version loading the localhost:3000 (from npm run dev) with loadURL
another version loading the built version (from npm run build)from the dist folder with loadFile
I have set in the new BrowserWindow options:
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
preload: path.join(app.getAppPath(), 'electron.preload.js')
}
The app starts just fine in Electron in both dev and build version, loads all assets and without any security errors. However, when I try to import any module from 'electron' in my project, in example:
import electron from 'electron';
I get the error:
Uncaught TypeError: path.join is not a function
at node_modules/electron/index.js (index.js:4)
I tried to check path and __dirname, to see if they work in my project:
import * as path from 'path';
console.log(path);
console.log(path.join);
console.log(__dirname);
And these do trace out the following in Electron dev panel:
If I try to import path differntly:
import path from 'path'
console.log(path);
console.log(path.join);
I get the following result:
In any case, path.join is undefined. And now I am pretty much stuck on how to go on.
I can also add that I want to use fs-extra, but this also fails:
import fs from 'fs-extra';
[Edit: added the preload in webPreferences]
I believe Vite transforms things a lot behind the scenes. Thankfully #electron/remote provides an alternate way to fetch things:
electron.js:
const { app, BrowserWindow } = require("electron");
const Remote = require("#electron/remote/main");
Remote.initialize();
// ...
app.on("ready", () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
});
Remote.enable(mainWindow.webContents);
mainWindow.loadFile(path.resolve("./dist", "index.html"));
});
// ...
Component.tsx:
import type { BrowserWindow } from "electron";
const Component: React.FC = () => {
const app = window.require("#electron/remote");
const win: BrowserWindow = app.getCurrentWindow();
// ...
}
Not sure if this is the best solution, but it works for me with Vite + Electron + React.
Related
I have just started using Electron.
This is the start of my preload.js:
const { contextBridge } = require('electron');
require('dotenv').config();
// ...
When I used npm start, the app started normally, except that the preload.js didn't do anything. I opened the developer tools and saw this error:
Error: module not found: dotenv
at preloadRequire (...)
...
Then I checked my npm-shrinkwrap.json:
"devDependencies": {
// ...
"dotenv": "^16.0.3",
"electron": "^22.1.0"
}
Well, it sure had dotenv.
So, how can I make preload.js be able to use dotenv?
Thanks to Alexander Leithner, I worked out the problem.
In the documentation, it says the 'sandbox' limits what I can 'require' from preload.js; so to disable it, set sandbox: false or nodeIntegration: true in webPreferences in the BrowserWindow options.
Example
app.whenReady().then(() => {
const win = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
})
win.loadURL('https://google.com')
})
Failed to load resource: net::ERR_FILE_NOT_FOUND
I am using latest version of npm, node.js and electron.
My html file calls upon a terrautils.js:
<script type="module" src="./terrautils.js"></script>
My terrautils.js file has first line as:
import { LCDClient, Coin } from './node_modules/#terra-money/terra.js';
Which is the link to an npm module that I want to use, and I have it installed and have confirmed that the folder is really there using file explorer. I also know the module works perfectly file, because this issue only happens when I run using npm start but when I run using node terrautils.js and swap from using import to using require, it works perfectly fine.
This is something to do with electron I think, and not sure what to do. My main.js has createWindow function like:
function createWindow (site) {
var win = new BrowserWindow({
width: 700,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: true,
devTools: true,
}
})
win.loadFile(site)
}
I do not care about security, I just want this to work. Thank you.
Solution:
Change html invoking of the js file to this instead:
<script>
require('./terrautils.js')
</script>
dont know how it works, but it does.
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 am trying to make a new Electron desktop app.
by the way, when I insert electron module, I get this error.
If you are familiar with electron, can you help me to resolve this error?
I already tried to fix it.
include require.js.
but not working yet.
<script>
const electron = require('electron'); // I get error at this line.
const {ipcRenderer} = electron;
const form = document.querySelector('form');
form.addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
}
</script>
If you are using Electron 5.0, then nodeIntegration is false by default in BrowserWindows so you need to specify it explicitly when you create your window:
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
You need to install electron
npm install electron --save-dev
--save-dev because electron is an development dependency.
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.