electron中main.js与自定义的JS文件,可以相到引用吗
在 Electron 中, `main.js`与自定义的 JavaScript 文件可以相互引用,但具体的方式取决于你希望自定义的 JS 文件运行在哪个进程中。以下是两种情况的实现方法:### 1. 在主进程中共享代码
如果你有一个自定义的 JS 文件,希望在主进程中使用(例如`main.js` ),可以使用 Node.js 的模块系统来导入和导出功能。
**示例:**
**main.js**
const { app, BrowserWindow } = require('electron');
const customModule = require('./custom.js'); // 导入自定义 JS 文件
app.on('ready', () => {
console.log(customModule.myFunction()); // 调用自定义模块中的函数
const win = new BrowserWindow({ width: 800, height: 600 });
win.loadFile('index.html');
});
**custom.js**
// custom.js
function myFunction() {
return "Hello from custom.js!";
}
module.exports = { myFunction }; // 导出函数
### 2. 在渲染进程中共享代码
如果你希望在渲染进程中使用自定义 JS 文件,通常需要使用 preload 脚本来安全地暴露某些功能。
**示例:**
**main.js**
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js') // 使用 preload 脚本
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
**preload.js**
const { contextBridge } = require('electron');
const customModule = require('./custom.js'); // 导入自定义 JS 文件
contextBridge.exposeInMainWorld('myAPI', {
myFunction: customModule.myFunction // 将函数暴露给渲染进程
});
**custom.js**
// custom.js
function myFunction() {
return "Hello from custom.js!";
}
module.exports = { myFunction }; // 导出函数
**index.html(或包含的脚本)**
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Electron App</title>
</head>
<body>
<script>
console.log(window.myAPI.myFunction()); // 调用暴露给渲染进程的函数
</script>
</body>
</html>
### 总结
- **在主进程中**:使用`require`直接导入自定义 JS 文件。
- **在渲染进程中**:使用 preload 脚本通过`contextBridge`安全地暴露函数或变量。
通过这种方式,你可以有效地在主进程和自定义 JavaScript 文件之间共享和重用代码。
页:
[1]