首页 > 解决方案 > 如何从所需模块中的 main.js 文件中访问变量?

问题描述

我开始使用 Electron,我想知道如何从 main.js 文件头部的必需脚本中访问存在于我的 main.js 脚本中的变量。

这是我的愚蠢示例:

主.js:

const Electron = require('electron');
const App = Electron.app;
const menus = require('./assets/js/menus.js'); //this is the required script!

let myVar = false;

App.on('ready', function({
   myVar = true;
})

//trying with module.exports
module.exports = {
   myVar
}

菜单.js:

const Path = require('path');
const main = require(Path.resolve('./main.js'));

Main: [{
        label:'mainLabel',
        submenu:[{
            label:'subLabel',
            click:()=>{
                console.log(**main.myVar**)//should be true when i access it, its undefined like it doesn't exists:(
            }
        }]
}]

我设法用 main.js 中的 getter 和 setter 做我想做的事,但我觉得这不是最好的方法。

有什么想法吗?有没有办法包含一个脚本,以便它可以访问脚本中声明的所有变量和函数,包括它?

标签: requirejselectron

解决方案


推荐阅读