创建应用程序
创建 Electron 应用
使用 Webpack 创建新的 Electron 应用程序:
npm init electron-app@latest my-new-app -- --template=webpack
启动应用
npm start
设置 Webpack 配置
添加依赖包,确保可以正确使用 JSX 和其他 React 功能:
npm install --save-dev @babel/core @babel/preset-react babel-loader
修改配置文件:
// webpack.rules.js
module.exports = [
// ... existing loader config ...
{
test: /\.jsx?$/,
use: {
loader: 'babel-loader',
options: {
exclude: /node_modules/,
presets: ['@babel/preset-react']
}
}
}
// ... existing loader config ...
];
集成前端 React
添加 React 依赖
将基本的 React 包添加到 dependencies:
npm install --save react react-dom
集成 React 代码
现在可以开始在 Electron 中编写和使用 React 组件了。在 src/app.jsx
中编写 React 代码:
import * as React from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.body);
root.render(<h2>Hello from React!</h2>);
添加渲染进程
将 React 代码添加到渲染进程 src/renderer.js
中:
import './index.css';
import './app.jsx';
console.log('👋 This message is being logged by