在 Electron 中需要 main
Require main in Electron
我有一个电子应用程序
exports.sayWord = function(){
console.log("some word")
};
在 main.js 中。现在,在renderer.js
,我有
const main = require('./main.js');
但是当我 运行 应用程序并打开 devtools 时出现错误:
Uncaught TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (/home/sean/elecapp/main.js:47:4)
at Object.<anonymous> (/home/sean/elecapp/main.js:70:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/sean/elecapp/renderer.js:20:14)
第 47 行是:
app.on('ready', createWindow);
但这没有意义,因为创建了 window,所以显然 electron 知道 app
和 createWindow
是什么。我怀疑这个问题与我需要 main.js
这一事实有关,因为我将函数 sayWord
放在其他文件中,当我需要这些文件时没有任何错误。
如果我没理解错的话,这是你的第一个电子项目,你不能创建你的 index.html?
这是我使用的 main.js 代码。它会将 index.html 加载到与启动网站相同的文件夹中。您不需要在 index.html
中导入 main.js
const {app, BrowserWindow, Tray, globalShortcut} = require('electron')
// this should be placed at top of main.js to handle setup events quickly
if (handleSquirrelEvent(app)) {
// squirrel event handled and app will exit in 1000ms, so don't do anything else
return;
}
const packager = require('electron-packager');
const path = require('path');
const url = require('url');
const mysql = require('mysql');
const loop = require('serial-loop');
const simpleTimestamp = require('simple-timestamp');
// 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 () {
win = new BrowserWindow({
width: 980,
height: 620,
resizable: true,
maximizable: true,
center: true,
webPreferences: {
nodeIntegration: true
} // webPreferences
}) // win = new BrowserWindow({
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
// win.webContents.openDevTools()
// mit zurück taste kann man auch in app zurück gehen
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
// 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.
function handleSquirrelEvent(application) {
if (process.argv.length === 1) {
return false;
}
const ChildProcess = require('child_process');
const path = require('path');
const appFolder = path.resolve(process.execPath, '..');
const rootAtomFolder = path.resolve(appFolder, '..');
const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
const exeName = path.basename(process.execPath);
const spawn = function(command, args) {
let spawnedProcess, error;
try {
spawnedProcess = ChildProcess.spawn(command, args, {
detached: true
});
} catch (error) {}
return spawnedProcess;
};
const spawnUpdate = function(args) {
return spawn(updateDotExe, args);
};
const squirrelEvent = process.argv[1];
switch (squirrelEvent) {
case '--squirrel-install':
case '--squirrel-updated':
// Optionally do things such as:
// - Add your .exe to the PATH
// - Write to the registry for things like file associations and
// explorer context menus
// Install desktop and start menu shortcuts
spawnUpdate(['--createShortcut', exeName]);
setTimeout(application.quit, 1000);
return true;
case '--squirrel-uninstall':
// Undo anything you did in the --squirrel-install and
// --squirrel-updated handlers
// Remove desktop and start menu shortcuts
spawnUpdate(['--removeShortcut', exeName]);
setTimeout(application.quit, 1000);
return true;
case '--squirrel-obsolete':
// This is called on the outgoing version of your app before
// we update to the new version - it's the opposite of
// --squirrel-updated
application.quit();
return true;
}
};
出现错误的原因是主进程和渲染进程无法访问相同的模块。例如 app
可以在主进程中直接通过 const {app} = require("electron")
访问,但在渲染器中你只能通过 const {app} = require("electron").remote
访问代理对象。但是你不应该使用 remote.app
来解决你的问题。如果您要在主进程和渲染器进程上将 main.js 脚本修改为 运行,您可能会创建一个循环来创建新的 windows!
您应该将 sayWord
外包给其他文件。如果您打算在主渲染器和渲染器之间发送数据,那么我建议改用 ipcMain and ipcRenderer。
我有一个电子应用程序
exports.sayWord = function(){
console.log("some word")
};
在 main.js 中。现在,在renderer.js
,我有
const main = require('./main.js');
但是当我 运行 应用程序并打开 devtools 时出现错误:
Uncaught TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (/home/sean/elecapp/main.js:47:4)
at Object.<anonymous> (/home/sean/elecapp/main.js:70:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/sean/elecapp/renderer.js:20:14)
第 47 行是:
app.on('ready', createWindow);
但这没有意义,因为创建了 window,所以显然 electron 知道 app
和 createWindow
是什么。我怀疑这个问题与我需要 main.js
这一事实有关,因为我将函数 sayWord
放在其他文件中,当我需要这些文件时没有任何错误。
如果我没理解错的话,这是你的第一个电子项目,你不能创建你的 index.html?
这是我使用的 main.js 代码。它会将 index.html 加载到与启动网站相同的文件夹中。您不需要在 index.html
中导入 main.jsconst {app, BrowserWindow, Tray, globalShortcut} = require('electron')
// this should be placed at top of main.js to handle setup events quickly
if (handleSquirrelEvent(app)) {
// squirrel event handled and app will exit in 1000ms, so don't do anything else
return;
}
const packager = require('electron-packager');
const path = require('path');
const url = require('url');
const mysql = require('mysql');
const loop = require('serial-loop');
const simpleTimestamp = require('simple-timestamp');
// 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 () {
win = new BrowserWindow({
width: 980,
height: 620,
resizable: true,
maximizable: true,
center: true,
webPreferences: {
nodeIntegration: true
} // webPreferences
}) // win = new BrowserWindow({
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
// win.webContents.openDevTools()
// mit zurück taste kann man auch in app zurück gehen
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
// 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.
function handleSquirrelEvent(application) {
if (process.argv.length === 1) {
return false;
}
const ChildProcess = require('child_process');
const path = require('path');
const appFolder = path.resolve(process.execPath, '..');
const rootAtomFolder = path.resolve(appFolder, '..');
const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
const exeName = path.basename(process.execPath);
const spawn = function(command, args) {
let spawnedProcess, error;
try {
spawnedProcess = ChildProcess.spawn(command, args, {
detached: true
});
} catch (error) {}
return spawnedProcess;
};
const spawnUpdate = function(args) {
return spawn(updateDotExe, args);
};
const squirrelEvent = process.argv[1];
switch (squirrelEvent) {
case '--squirrel-install':
case '--squirrel-updated':
// Optionally do things such as:
// - Add your .exe to the PATH
// - Write to the registry for things like file associations and
// explorer context menus
// Install desktop and start menu shortcuts
spawnUpdate(['--createShortcut', exeName]);
setTimeout(application.quit, 1000);
return true;
case '--squirrel-uninstall':
// Undo anything you did in the --squirrel-install and
// --squirrel-updated handlers
// Remove desktop and start menu shortcuts
spawnUpdate(['--removeShortcut', exeName]);
setTimeout(application.quit, 1000);
return true;
case '--squirrel-obsolete':
// This is called on the outgoing version of your app before
// we update to the new version - it's the opposite of
// --squirrel-updated
application.quit();
return true;
}
};
出现错误的原因是主进程和渲染进程无法访问相同的模块。例如 app
可以在主进程中直接通过 const {app} = require("electron")
访问,但在渲染器中你只能通过 const {app} = require("electron").remote
访问代理对象。但是你不应该使用 remote.app
来解决你的问题。如果您要在主进程和渲染器进程上将 main.js 脚本修改为 运行,您可能会创建一个循环来创建新的 windows!
您应该将 sayWord
外包给其他文件。如果您打算在主渲染器和渲染器之间发送数据,那么我建议改用 ipcMain and ipcRenderer。