【问题标题】:Require main in Electron在 Electron 中需要 main
【发布时间】:2018-01-07 15:43:48
【问题描述】:

在我的电子应用中

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);

但这没有意义,因为创建了窗口,所以显然电子知道 appcreateWindow 是什么。我怀疑这个问题与我需要 main.js 的事实有关,因为我将函数 sayWord 放在其他文件中,而当我需要时,这些都没有问题。

【问题讨论】:

    标签: node.js electron require


    【解决方案1】:

    如果我理解正确,这是你的第一个电子项目,你不能创建你的 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;
        }
    };
    

    【讨论】:

      【解决方案2】:

      您收到错误的原因是主进程和渲染器进程无法访问相同的模块。例如app 可以在主进程中直接通过const {app} = require("electron") 访问,但在渲染器中您只能通过const {app} = require("electron").remote 访问代理对象。但是您也不应该使用remote.app 来解决您的问题。如果您要修改 main.js 脚本以在主进程和渲染器进程上运行,您可能会创建一个创建新窗口的循环!

      您应该将sayWord 外包给另一个文件。如果您打算在主渲染器和渲染器之间发送数据,那么我建议您改用ipcMainipcRenderer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-30
        • 2018-08-26
        • 2018-04-05
        • 2011-05-06
        • 2010-10-14
        • 2021-05-26
        • 1970-01-01
        • 2014-03-13
        相关资源
        最近更新 更多