多个文件中的拆分电子主过程:不能使用相同的`global`

问题描述 投票:0回答:1

我需要一些有关主进程和渲染器进程的解释。尽管我理解了,但我现在对此表示怀疑(并且我还需要帮助调试主要过程...)

如果我理解this:主要过程是主js文件中所有required的js文件,它们可以使用appBrowserWindow,[...]等。渲染器进程是包含在<script>标签?

的html文件中的所有javascript。

我将主进程分割为多个文件,global是否对所有这些文件都通用?我在main.js中定义了global.sharedThing = { ... },但是当我尝试使用global.sharedThing.label = 'other Str'在另一个js文件中覆盖它时,却出现了以下错误消息:

enter image description here

我的文件夹结构:

<root>
    └─ app
        ├─ [...]
        ├─ windows
        │    └─ tests
        │        ├─ index.js
        │        ├─ script.js
        │        └─ view.html
        └─ main.js

哪里

  • main.js =应用入口点(electron .
  • index.js = main.js必需,使用BrowserWindow和ipcMain管理窗口
  • script.js =在index.html中使用,在中,处理一些JQuery并使用ipcRendererremote
  • view.html =窗口中加载的html文件

../ app / main.js

'use strict'

const { app } = require('electron');

const test = require('./windows/tests');

console.log('test debug from main.js'); // don't appear anywhere

global.sharedThing = {
  label: 'Shared from main.js'
};

function Init() {
  test.Create();
}

app.on('ready', Init);

./ app / windows / tests / index.js

const { app, BrowserWindow, ipcMain } = require('electron');

let win = null;

// global.sharedThing.label = 'Shared updated from index.js'; // <== THROW ERROR IF UNCOMMENT

function Create() {
    if(win) return win;

    win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  win.loadFile(path.join(__dirname, '/view.html'));

  win.on('closed', () => {
    win = null;
  });
}

module.exports = {
    Create,
}

.. app / windows / tests / script.js

const { ipcRenderer } = require('electron');

window.jQuery = window.$ = require('jquery');

const sharedThing = require('electron').remote.getGlobal('sharedThing');

$(document).ready(function() {
  $('#testBtn').on('click', onClick);
})

function onClick() {
  console.log('sharedThing', sharedThing); // works
}

./ app / windows / tests / view.html

        <!-- hidden for brevity -->
    <script src="./script.js"></script>
  </head>
  <body>
    <button type="button" id="testBtn" value="Click me!">Yes!</button>
    <!-- hidden for brevity -->
node.js electron global
1个回答
0
投票

您的main.js是逐行执行的,因此如果您查看它,就会显示const test = require('./windows/tests');出现在[[before中,sharedThing全局已设置。这意味着windows/tests/index.js中的所有代码在global.sharedThing被赋值之前就已经执行了,因此,当您尝试访问它时,它仍然是未定义的。

要解决它,只需将global.sharedThing = ...声明移到依赖于它的文件的require语句之前。
© www.soinside.com 2019 - 2024. All rights reserved.