Geo*_*tan 9 node.js electron electron-forge
我刚刚使用以下命令创建了一个新应用程序:
npx create-electron-app my-new-app --template=typescript-webpack
Run Code Online (Sandbox Code Playgroud)
在renderer.ts 中,我添加了以下代码
import "./index.css";
import { ipcRenderer } from "electron";
Run Code Online (Sandbox Code Playgroud)
但是当我运行npm run start 时,浏览器控制台中出现以下错误
Uncaught ReferenceError: require is not defined
Run Code Online (Sandbox Code Playgroud)
更新 我尝试过的内容:
webpack.plugins.js
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const webpack = require("webpack");
module.exports = [
new ForkTsCheckerWebpackPlugin(),
new webpack.ExternalsPlugin("commonjs", ["electron"]),
];
Run Code Online (Sandbox Code Playgroud)
但它仍然不起作用。
Geo*_*tan 18
找到解决方案
解决方案是在预加载脚本中使用 ipcRenderer。
预载.ts
import { ipcRenderer } from "electron";
Run Code Online (Sandbox Code Playgroud)
索引.ts
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: any;
const mainWindow = new BrowserWindow({
height: 600,
width: 800,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
Run Code Online (Sandbox Code Playgroud)
包.json
"plugins": [
[
"@electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.ts",
"name": "main_window",
"preload": {
"js": "./src/preload.ts"
}
}
]
}
}
]
]
Run Code Online (Sandbox Code Playgroud)
解决方案是使用Electron-Forge React+Webpack模板ContextBridge中的 APIelectron
预加载.js
import { ipcRenderer, contextBridge } from "electron";
contextBridge.exposeInMainWorld("electron", {
notificationApi: {
sendNotification(message) {
ipcRenderer.send("notify", message);
},
},
batteryApi: {},
fileApi: {},
});
Run Code Online (Sandbox Code Playgroud)
main.js
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
worldSafeExecuteJavaScript: true,
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
ipcMain.on("notify", (_, message) => {
new Notification({ title: "Notification", body: message }).show();
});
Run Code Online (Sandbox Code Playgroud)
包.json
"plugins": [
[
"@electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.js",
"name": "main_window",
"preload": {
"js": "./src/preload.js"
}
}
]
}
}
]
]
Run Code Online (Sandbox Code Playgroud)
应用程序.jsx
import * as React from "react";
import * as ReactDOM from "react-dom";
class App extends React.Component {
componentDidMount() {
electron.notificationApi.sendNotification("Finally!");
}
render() {
return <h1>contextBridge</h1>;
}
}
ReactDOM.render(<App />, document.body);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2274 次 |
| 最近记录: |