electron之旅(二)react使用

首先使用react模板

我们这里使用的是vite和yarn

yarn create vite #创建vite的react-js模板

electron之旅(二)react使用_第1张图片

初始化依赖

yarn

添加依赖

state(状态管理)

yarn add redux react-redux

routes(react路由)

yarn add react-router-dom

electron依赖

yarn add electron vite-plugin-electron cross-env -D

修改&添加文件

创建(根目录(与src同级))\electron/index.js

import { app, BrowserWindow } from "electron";
import path from "path";

const createWindow = () => {
  const win = new BrowserWindow({
    webPreferences: {
      // 允许渲染进程使用node
      contextIsolation: false,
      nodeIntegration: true,
    },
  });
  // app.isPackaged 字段存在bug,即使正常打包后,仍然为false,所以不能用来判断项目是否经过打包
  if (process.env.NODE_ENV === 'development') {
    // 开发环境
    // process.env.VITE_DEV_SERVER_URL获取开发服务器的url
    // vite版本不同,VITE_DEV_SERVER_URL字段也有所变化,打印process.env查找具体的名称
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
  } else {
    // 生产环境
    win.loadFile(path.join(__dirname, "../dist/index.html"));
  }
};

app.whenReady().then(createWindow)

package.json

{
  "name": "electron_react_js_test01",
  "private": true,
  "version": "0.0.0",
  "type": "commonjs",//修改
  "main": "dist-electron/index.js",//添加
  "scripts": {
    "dev": "cross-env NODE_ENV=development vite",//修改
    "build": "vite build",
    "preview": "vite preview"
  },
  ...
}

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

import electron from "vite-plugin-electron"//添加

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    //添加
    electron({
      entry: 'electron/index.js'
    })
  ],
})

yarn dev #即可

react状态管理&react路由

store.js

import {legacy_createStore} from "redux"

//当然里面的数据自定义,这里只是一个参照
const defaultState = {
    num:0,
    isHome:false
}

const reducer = (state = defaultState,action = {type,data}) =>{
  //深拷贝
  let newState = JSON.parse(JSON.stringify(state))

  //当然里面的数据自定义,这里只是一个参照
  switch(action.type){
    case "returnHome":
        newState.isHome = true
        break
    case "QiTaPage":
        newState.isHome = false
        break
    default:
        break
  }

  return newState
}

const store = legacy_createStore(reducer)

export default store


routes.jsx

import { Navigate } from "react-router-dom"
import Master from "./pages/master/Master"
import Home from "./pages/master/home/Home"
import Anime from "./pages/master/anime/Anime"

const routes = [
    {
        path: '/master',
        element: <Master />,
        children: [
            {
                path: 'home',
                element: <Home />
            },
            {
                path: 'anime',
                element: <Anime />
            }
        ]
    }
]


export default routes

main.jsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import { Provider } from 'react-redux'
import { HashRouter } from 'react-router-dom'
import store from './store'

ReactDOM.createRoot(document.getElementById('root')).render(
  <Provider store={store}>
    <HashRouter>
      <App />
    </HashRouter>
  </Provider>
)

./src/App.jsx


渲染进程react和主进程通讯

渲染进程(以创建窗口为例)

import {useState, useEffect} from "react"
import { useSelector,useDispatch } from "react-redux"

import { ipcRenderer } from "electron"//主要引入

import anime from './anime.module.css'

function Anime(props){
    return (
        <div className={anime.all}>
        	{/*主要*/}
            <button onClick={()=>ipcRenderer.send('new-win')}>点击新页面</button>
        </div>
    )
}

export default Anime

主进程(以创建窗口为例)

import { app, BrowserWindow, ipcMain } from "electron";
import path from "path";

const createWindow = () => {
  const win = new BrowserWindow({...});
  //添加
  ipcMain.on('new-win',()=>{
    const newWin = new BrowserWindow({
        width:300,
        height:250,
        webPreferences: {
            // 允许渲染进程使用node
            contextIsolation: false,
            nodeIntegration: true,
        },
    })
    newWin.loadURL("https://www.bilibili.com") //可以自行修改
  })
....

问题1

TypeError: path.join is not a function

electron之旅(二)react使用_第2张图片

解决
yarn add vite-plugin-electron-renderer

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

import electron from "vite-plugin-electron"

import electron_render from "vite-plugin-electron-renderer" //添加
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    electron({
      entry: 'electron/index.js'
    }),
    electron_render()//添加
  ],
})

你可能感兴趣的:(electron,react.js,electron,javascript)