我需要一些有关主进程和渲染器进程的解释。尽管我理解了,但我现在对此表示怀疑(并且我还需要帮助调试主要过程...)
如果我理解this:主要过程是主js文件中所有required
的js文件,它们可以使用app
,BrowserWindow
,[...]等。渲染器进程是包含在<script>
标签?
我将主进程分割为多个文件,global
是否对所有这些文件都通用?我在main.js中定义了global.sharedThing = { ... }
,但是当我尝试使用global.sharedThing.label = 'other Str'
在另一个js文件中覆盖它时,却出现了以下错误消息:
我的文件夹结构:
<root>
└─ app
├─ [...]
├─ windows
│ └─ tests
│ ├─ index.js
│ ├─ script.js
│ └─ view.html
└─ main.js
哪里
electron .
)ipcRenderer
和remote
../ 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 -->
您的main.js
是逐行执行的,因此如果您查看它,就会显示const test = require('./windows/tests');
出现在[[before中,sharedThing
全局已设置。这意味着windows/tests/index.js
中的所有代码在global.sharedThing
被赋值之前就已经执行了,因此,当您尝试访问它时,它仍然是未定义的。
global.sharedThing = ...
声明移到依赖于它的文件的require语句之前。