在搭建electron的ts实现遇到了一些坑,花费了不少时间,这里需要用到 一个node包,react-app-rewired
,主要是为了修改默认的cra webpack配置,把target目标设置成“electron-renderer”,可以解决在node环境库不能执行问题,具体实现如下
创建cra 环境
1
yarn create react-app my-app --template typescript
安装包
react-app-rewired
方便自定义配置webpack1
yarn add -D react-app-rewired
修改package.json 启动命令,通过 react-app-rewired 命令启动
1
2
3
4"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
在工程目录下创建webpack 自定义配置文件
config-overrides.js
,修改编译目标为electron-renderer
1
2
3
4module.exports = function override(config, env) {
config.target = 'electron-renderer'
return config;
}安装electron
1
yarn add -D electron
在工程目录下public文件下创建
electron.js
文件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const { app, BrowserWindow } = require('electron')
function createWindow () {
// Create the browser window.
let win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadURL('http://localhost:3666')//注意端口号,要与启动命令中配置一致
}
app.whenReady().then(createWindow)再次配置package.json的入口文件相关字段
1
2
3
4
5{
"homepage": "./",
"main": "./public/electron.js",
"license":"ISC",
}安装node包
concurrently
和wait-on
1
yarn add -D concurrently wait-on
修改package.json启动命令配置
1
2
3
4
5
6
7
8
9
10{
"scripts": {
"estart": "concurrently -k \"BROWSER=none PORT=3666 react-app-rewired start\" \"wait-on http://localhost:3666 && electron .\"",
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
}启动electron,成功
1
yarn estart
备注,这样在react App中导入node 库就可以正常执行了。如果不需要node环境,那么在webPreferences
的node 配置设置为false, webpack 的target也不需要设置。github 地址:https://github.com/wushshsha/electron-create-react-app-typescript-template.git