electron开发笔记

安装Electron

• Mac/Linux: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/
install.sh | bash

• Windows: https://github.com/coreybutler/nvm-windows/releases
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

# ~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc,选择环境使用bash
source ~/.zshrc

• 安装 Node.js: nvm install 12.14.0

• 切换 Node.js 版本:nvm use 12.14.0

• 验证 npm -v

• 验证 node -v
• npm install electron --save-dev

• npm install --arch=ia32 --platform=win32 electron

• 验证安装成功:

• npx electron -v

• ./node_modules/.bin/electron -v

问题:
安装electron提示版本不匹配
使用 18.10.0 版本ok
npx electron -v 提示找不到exe,但是直接运行 electron OK

开发

#创建项目并进入主目录
cd remote_desktop/

#初始化
npm init -y

#创建项目结构
mkdir app
mkdir app/main
mkdir app/renderer
mkdir app/renderer/src
mkdir app/renderer/pages
mkdir app/renderer/pages/control
#控制窗口
touch app/renderer/pages/control/index.html
<html>
    <body>
        control
    </body>
</html>
#进入src,生成react脚手架
cd app/renderer/src
npx create-react-app main --use-npm

#安装完提示
cd main
npm start
#于是http://localhost:3000/可以访问一个react页面

#cd 到 remote_desktop/app/main 下面 创建主进程的js
touch index.js

const {app,BrowserWindow} = require('electron')

var win 
app.on('ready',()=>{
    win = new BrowserWindow({
        width: 600,
        height:300,
        webPrefences:{
            nodeIntegration: true
        }
    })

    win.loadURL('http://localhost:300')
})

修改package.json,添加启动指令

{
  "name": "remote_desktop",
  "version": "1.0.0",
  "description": "",
  //修改main进程的js路径
  "main": "app/main/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    //启动main进程
    "start:main": "electron .",
    //启动render进程
    "start:render": "cd app/renderer/src/main && npm start"
  },

  "keywords": [],
  "author": "",
  "license": "ISC"
}
正式运行的json中要删除以上注释,否则不能识别报错

#运行前先指定nmv版本,如上面所诉
npm run start:render
npm run start:main

效果如图

启动render进程自动打开浏览器

vi renderer/src/main/package.json
添加参数:BROWSER=none 
  "scripts": {
    "start": "BROWSER=none react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
cd app/renderer/src/main/ && npm i customize-cra react-app-rewired --save-dev
npm i electron-is-dev   
npm rebuild -runtime=electron -disturl=https://atom.io/download/atom-shell -target=7.1.8 -abi=72

posted @ 2023-03-20 22:10  懒企鹅  阅读(33)  评论(0编辑  收藏  举报