1. 安装react工具
npm install -g create-react-app
2. 采用默认参数创建一个工程
create-react-app myapp
这会创建一个目录myapp, 同时初始化一个node工程
待命令执行完成,
npm start: 运行服务在3000端口, 打开浏览器.
npm run build: 打包react代码.
3. 安装electron
npm run electron --save-dev
最后一步> node install.js会从github下载一个二进制的electron, 可能会出各种问题, 最好翻个墙.
4. 安装electron-builder, 安装在当前项目下
npm install electron-builder --save-dev
5. 添加electron的入口文件.
最好放到public下, 命名为electron.js
文件内容如下
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const isDev = require('electron-is-dev');
const path = require('path');
let mainWindow;function createWindow() {
mainWindow = new BrowserWindow({width: 900, height: 680});
//mainWindow.loadURL('http://localhost:3000');
mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`);
app.setAboutPanelOptions({
applicationName: "Mook",
applicationVersion: "0.0.1",
})mainWindow.on('closed', () => mainWindow = null);
}app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
这段主要来源与electron的github官网, 只修改了mainWindow.loadURL, 可以同时支持dev和product模式.
package.json文件添加入口
增加"main": "public/electron.js",
package.json里增加react的homepage
"homepage":".",
这样, 最终的package文件是这样的.
{
"name": "bw",
"version": "0.1.0",
"private": true,
"homepage":".",
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^7.2.1",
"electron-is-dev": "^1.1.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.0"
},
"main": "public/electron.js",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"dist": "electron-builder --config.extraMetadata.main=build/electron.js",
"dev": "ELECTRON_IS_DEV=1 electron .",
"main": "ELECTRON_IS_DEV=0 electron ."
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"electron": "^7.1.7",
"electron-builder": "^21.2.0"
}
}
6. build release版本
./node_modules/.bin/electron-builder .