javascript - 当我尝试将 js 文件(带有节点模块)导入到我的主电子 js 文件时出现“未定义要求”错误
问题描述
嗨,我是electron.js的新手,我遇到了一个问题,即我无法在main.js 文件中捕获 jquery 事件。作为解决方案,我创建了一个单独的文件(events.js)[现在我可以捕获 jquery 事件]并将其连接到index.html。所以在我的event.js中,我添加了一个cron-job(node-cron)来检查它是否正常工作,但是当我尝试运行一个项目时,我收到一个错误,说require is not defined。没有任何导入库,它就可以工作。
这是我的index.html
<body>
<div style="margin-top:15px" class="container">
<div class="row">
<div class="col-xs-3">
<a class="btn btn-info btn-sm btn-block" href="./layouts/settings.html" id="menu-btn-settings"
role="button">Settings</a>
<a class="btn btn-info btn-sm btn-block" href="./layouts/health.html" id="menu-btn-health"
role="button">System Health</a>
<a class="btn btn-info btn-sm btn-block" href="./layouts/abc-now.html" id="menu-btn-abc-now"
role="button">Sync Now</a>
<a class="btn btn-info btn-sm btn-block" href="./layouts/abc-customer.html" id="menu-btn-abc-user"
role="button">Sync
Customer</a>
<a class="btn btn-info btn-sm btn-block" href="./layouts/about.html" id="menu-btn-about"
role="button">About</a>
</div>
<div class="col-xs-9">
<div id="alert-msg"></div>
<div id="content"></div>
</div>
</div>
</div>
<!-- Insert this line above script imports -->
<script>if (typeof module === 'object') { window.module = module; module = undefined; }</script>
<script src="./assets/js/jquery-3.4.1.min.js"></script>
<script src="./assets/js/bootstrap.min.js"></script>
//
<script src="./main.js"></script>
<script src="./app/events.js"></script>
<script src="./assets/js/require.js"></script>
<script>if (window.module) module = window.module;</script>
</body>
这是我的 main.js
app.on('ready', function () {
win = new BrowserWindow({});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: false,
webPreferences: {
nodeIntegration: true,
},
}));
win.on('closed', function () {
app.quit();
});
win.webContents.openDevTools();
});
这是我的event.js
(function () {
'use strict';
var CronJob = require('cron').CronJob;
var job = new CronJob('* * * * * *', function () {
console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');
job.start();
})();
解决方案
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
})
webPreferences
从选项中删除win.loadURL
并添加到BrowserWindow
选项。以下是启用 Node api 的示例代码BrowserWindow
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
推荐阅读
- python - Python 默认参数列表强行为
- azure - 无法访问 LUIS 门户
- kubernetes - 我们如何在我的 k8s 集群中修改 docker0 mtu?
- c# - 如何将 local.settings.json 从 azure 函数移植到 .NET 核心 Web 项目?
- ios - 是否可以对 iOS 框架进行代码分析?
- javascript - 如何将画布编辑的图像数据获取到 HTML 输入字段?
- google-play-console - Google Play 控制台发出安全警报 - 易受攻击
- c++ - 将基类静态转换为派生指针并构造派生成员
- powershell - 如何在powershell中排除选定文件的列表
- postgresql - 无法将 NodeJs 应用程序与在 Minikube 中运行的 Postgres 连接