使用React、Electron、Dva、Webpack、Node.js、Websocket快速構建跨平臺應用

圖片描述

目前Electrongithub上面的star量已經快要跟React-native同樣多了

這裏吐槽下, webpack感受每週都在偷偷更新,很糟心啊,還有 Angular更新到了 8, Vue立刻又要出正式新版本了, 5G今年就要商用,華爲的系統也要出來了, RN尚未更新到正式的 1版本,還有號稱讓前端開發者失業的技術 flutter也在瘋狂更新,前端真的是學不完的

圖片描述
圖片描述

回到正題,不可否認,如今的大前端,真的太牛了, PC端能夠跨三種平臺開發,移動端能夠一次編寫,生成各類小程序以及 React-native應用,而後跑在 ios和安卓以及網頁中 , 這裏不得不說-------京東的 Taro框架 這些人 已經把 Node.jswebpack用上了天

webpack不熟悉的,看我以前的文章 ,今天不把重點放在webpackcss

歡迎關注個人專欄 《前端進階》 都是百星高贊文章html

先說說Electron官網介紹:

使用 JavaScript, HTML 和 CSS 構建跨平臺的桌面應用 ,若是你能夠建一個網站,你就能夠建一個桌面應用程序。 Electron 是一個使用 JavaScript, HTML 和 CSS 等 Web 技術建立原生程序的框架,它負責比較難搞的部分,你只需把精力放在你的應用的核心上便可。

  • 什麼意思呢?
  • Electron = Node.js + 谷歌瀏覽器 + 日常的JS代碼生成的應用,最終打包成安裝包,就是一個完整的應用
  • Electron分兩個進程,主進程負責比較難搞的那部分,渲染進程(日常的JS代碼)部分,負責UI界面展現
  • 兩個進程之間能夠經過remote模塊,以及IPCRenderIPCMain之間通訊,前者相似於掛載在全局的屬性上進行通訊(很像最先的命名空間模塊化方案),後者是基於發佈訂閱機制,自定義事件的監聽和觸發實現兩個進程的通訊。
  • Electron至關於給React生成的單頁面應用套了一層殼,若是涉及到文件操做這類的複雜功能,那麼就要依靠Electron的主進程,由於主進程能夠直接調用Node.jsAPI,還可使用C++插件,這裏Node.js的牛逼程度就凸顯出來了,既能夠寫後臺的CRUD,又能夠作中間件,如今又能夠寫前端。

談談技術選型

  • 使用React去作底層的UI繪製,大項目首選React+TS
  • 狀態管理的最佳實踐確定不是Redux,目前首選dva,或者redux-saga
  • 構建工具選擇webpack,若是不會webpack真的很吃虧,會嚴重限制你的前端發展,因此建議好好學習Node.jswebpack
  • 選擇了普通的Restful架構,而不是GraphQL,可能我對GraphQL理解不深,沒有領悟到精髓
  • 在通訊協議這塊,選擇了websoket和普通的http通訊方式
  • 由於是demo,不少地方並無細化,後期會針對electron出一個網易雲音樂的開源項目,這是必定要作到的

先開始正式的環境搭建

clipboard.png

  • config文件放置webpack配置文件
  • server文件夾放置Node.js的後端服務器代碼
  • src下放置源碼
  • main.jsElectron的入口文件
  • json文件是腳本入口文件,也是包管理的文件~

開發模式項目啓動思路:

  • 先啓動webpack將代碼打包到內存中,實現熱更新
  • 再啓動Electron讀取對應的url地址的文件內容,也實現熱更新

設置webpack入口

app: ['babel-polyfill', './src/index.js', './index.html'],
        vendor: ['react']
        }

忽略Electron中的代碼,不用webpack打包(由於Electron中有後臺模塊代碼,打包就會報錯)

externals: [
        (function () {
            var IGNORES = [
                'electron'
            ];
            return function (context, request, callback) {
                if (IGNORES.indexOf(request) >= 0) {
                    return callback(null, "require('" + request + "')");
                }
                return callback();
            };
        })()
    ]

加入代碼分割

optimization: {
        runtimeChunk: true,
        splitChunks: {
            chunks: 'all'
        }
    },

設置熱更新等

plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
    ],
    mode: 'development',
    devServer: {
        contentBase: '../build',
        open: true,
        port: 5000,
        hot: true
    },

#### 加入babel前端

{
    loader: 'babel-loader',
    options: {   //jsx語法
        presets: ["@babel/preset-react",
            //tree shaking 按需加載babel-polifill  presets從後到前執行 
            ["@babel/preset-env", {
                "modules": false,
                "useBuiltIns": "false", "corejs": 2,
            }],
        ],

    plugins: [
        //支持import 懶加載    plugin從前到後
        "@babel/plugin-syntax-dynamic-import",
        //andt-mobile按需加載  true是less,若是不用less style的值能夠寫'css' 
        ["import", { libraryName: "antd-mobile", style: true }],
        //識別class組件
        ["@babel/plugin-proposal-class-properties", { "loose": true }],
        //
    ],
    cacheDirectory: true
},
}

看看主進程的配置文件main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, Tray, Menu } = require('electron')
const path = require('path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
app.disableHardwareAcceleration()
// ipcMain.on('sync-message', (event, arg) => {
//   console.log("sync - message")
//   // event.returnValue('message', 'tanjinjie hello')
// })
function createWindow() {
  // Create the browser window.
  tray = new Tray(path.join(__dirname, './src/assets/bg.jpg'));
  tray.setToolTip('wechart');
  tray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
  });
  const contextMenu = Menu.buildFromTemplate([
    { label: '退出', click: () => mainWindow.quit() },
  ]);
  tray.setContextMenu(contextMenu);
  mainWindow = new BrowserWindow({
    width: 805,
    height: 500,
    webPreferences: {
      nodeIntegration: true
    },
    // titleBarStyle: 'hidden'
    frame: false
  })

  //自定義放大縮小托盤功能
  ipcMain.on('changeWindow', (event, arg) => {
    if (arg === 'min') {
      console.log('min')
      mainWindow.minimize()
    } else if (arg === 'max') {
      console.log('max')
      if (mainWindow.isMaximized()) {
        mainWindow.unmaximize()
      } else {
        mainWindow.maximize()
      }
    } else if (arg === "hide") {
      console.log('hide')
      mainWindow.hide()
    }
  })
  // and load the index.html of the app.
  // mainWindow.loadFile('index.html')
  mainWindow.loadURL('http://localhost:5000');
  BrowserWindow.addDevToolsExtension(
    path.join(__dirname, './src/extensions/react-dev-tool'),
  );


  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
    BrowserWindow.removeDevToolsExtension(
      path.join(__dirname, './src/extensions/react-dev-tool'),
    );
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) createWindow()
})


// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

今天只講開發模式下的配置,由於實在太多,得分兩篇文章寫了~ 剩下的配置去git倉庫看

在開發模式下啓動項目:

  • 使用 "dev": "webpack-dev-server --config ./config/webpack.dev.js", 將代碼打包到內存中
  • 使用 "start": "electron ." 開啓electron,讀取對應的內存地址中的資源,實現熱更新

項目起來後,在入口處index.js文件中,注入dva

import React from 'react'
import App from './App'
import dva from 'dva'
import Homes from './model/Homes'
import main from './model/main'
const app = dva()
app.router(({ history, app: store }) => (
  <App
    history={history}
    getState={store._store.getState}
    dispatch={store._store.dispatch}
  />
));
app.model(Homes)
app.model(main)
app.start('#root')

這裏不得不說redux,redux-sage,dva的區別 直接看圖

首先是Redux

  • React 只負責頁面渲染, 而不負責頁面邏輯, 頁面邏輯能夠從中單獨抽取出來, 變成 store,狀態及頁面邏輯從 <App/>裏面抽取出來, 成爲獨立的 store,
  • 頁面邏輯就是 reducer,<TodoList/> 及<AddTodoBtn/>都是 Pure Component, 經過 connect 方法能夠很方便地給它倆加一層 wrapper 從而創建起與 store 的聯繫: 能夠經過 dispatchstore 注入 action, 促使 store 的狀態進行變化, 同時又訂閱了 store 的狀態變化, 一旦狀態有變, 被 connect 的組件也隨之刷新,使用 dispatchstore 發送 action 的這個過程是能夠被攔截的, 天然而然地就能夠在這裏增長各類 Middleware, 實現各類自定義功能, eg: logging這樣一來, 各個部分各司其職, 耦合度更低, 複用度更高, 擴展性更好

這個是Redux

而後是注入Redux-sage

  • 上面說了, 可使用 Middleware 攔截 action, 這樣一來異步的網絡操做也就很方便了, 作成一個 Middleware 就好了, 這裏使用 redux-saga 這個類庫, 舉個栗子:
  • 點擊建立 Todo 的按鈕, 發起一個 type == addTodo 的 action
  • saga 攔截這個 action, 發起 http 請求, 若是請求成功, 則繼續向 reducer 發一個 type == addTodoSucc action, 提示建立成功, 反之則發送 type == addTodoFailaction 便可

最後是: Dva

  • 有了前面的三步鋪墊, Dva 的出現也就水到渠成了, 正如 Dva 官網所言, Dva 是基於 React + Redux + Saga 的最佳實踐沉澱, 作了 3 件很重要的事情, 大大提高了編碼體驗:
  • store saga 統一爲一個 model 的概念, 寫在一個 js 文件裏面
  • 增長了一個 Subscriptions, 用於收集其餘來源的 action, eg: 鍵盤操做
  • model 寫法很簡約, 相似於 DSL 或者 RoR, coding 快得飛起✈️
  • 約定優於配置, 老是好的😆

clipboard.png

clipboard.png

在入口APP組件中,注入props,實現狀態樹的管理

import React from 'react'
import { HashRouter, Route, Redirect, Switch } from 'dva/router';
import Home from './pages/home'
const Router = (props) => {
    return (
        <HashRouter>
            <Switch>
                <Route path="/home" component={Home}></Route>
                <Redirect to="/home"></Redirect>
            </Switch>
        </HashRouter>
    )
}
export default Router

在組件中connect鏈接狀態樹便可

import React from 'react'
import { ipcRenderer } from 'electron'
import { NavLink, Switch, Route, Redirect } from 'dva/router'
import Title from '../../components/title'
import Main from '../main'
import Friend from '../firend'
import More from '../more'
import { connect } from 'dva'
import './index.less'
class App extends React.Component {
    componentDidMount() {
        ipcRenderer.send('message', 'hello electron')
        ipcRenderer.on('message', (event, arg) => {
            console.log(arg, new Date(Date.now()))
        })
        const ws = new WebSocket('ws://localhost:8080');
        ws.onopen = function () {
            ws.send('123')
            console.log('open')
        }
        ws.onmessage = function () {
            console.log('onmessage')
        }
        ws.onerror = function () {
            console.log('onerror')
        }
        ws.onclose = function () {
            console.log('onclose')
        }
    }
    componentWillUnmount() {
        ipcRenderer.removeAllListeners()
    }
    render() {
        console.log(this.props)
        return (
            <div className="wrap">
                <div className="nav">
                    <NavLink to="/home/main">Home</NavLink>
                    <NavLink to="/home/firend">Friend</NavLink>
                    <NavLink to="/home/more">More</NavLink>
                </div>
                <div className="content">
                    <Title></Title>
                    <Switch>
                        <Route path="/home/main" component={Main}></Route>
                        <Route path="/home/firend" component={Friend}></Route>
                        <Route path="/home/more" component={More}></Route>
                        <Redirect to="/home/main"></Redirect>
                    </Switch>
                </div>
            </div>
        )
    }
}
export default connect(
    ({ main }) => ({
        test: main.main
    })
)(App)
// ipcRenderer.sendSync('sync-message','sync-message')

捋一捋上面的組件作了什麼

  • 上來在組件掛載的生命週期函數中,啓動了websocket鏈接,而且掛載了響應的事件監聽,對主線程發送了消息,而且觸發了主線程的message事件。
  • 在組件即將卸載的時候,移除了全部的跨進程通訊的事件監聽
  • 使用了dva進行路由跳轉
  • 鏈接了狀態樹,讀取了狀態樹main模塊的main狀態數據

進入上一個組件的子組件

import React from 'react'
import { connect } from 'dva'
class App extends React.Component {
    handleAdd = () => {
        this.props.dispatch({
            type: 'home/add',
            val: 5,
            res: 1
        })
    }
    handleDel = () => {
    }
    render() {
        const { homes } = this.props
        console.log(this.props)
        return (
            <div>
                <button onClick={this.handleAdd}>add</button>
                <button onClick={this.handleDel}>{homes}</button>
            </div>
        )
    }
}
export default connect(
    ({ home, main }) => ({
        homes: home.num,
        mains: main.main
    })
)(App)

一樣看看,這個組件作了什麼

  • 鏈接狀態樹,讀取了 home,main模塊的狀態數據,而且轉換成了props
  • 綁定了事件,若是點擊按鈕,dispatch給對應的effects,更新狀態樹的數據,進而更新頁面

最後咱們看下如何經過渲染進程控制主進程的窗口顯示

import React from 'react'
import { ipcRenderer } from 'electron'
import './index.less'
export default class App extends React.Component {
    handle = (type) => {
        return () => {
            if (type === 'min') {
                console.log('min')
                ipcRenderer.send('changeWindow', 'min')
            } else if (type === 'max') {
                console.log('max')
                ipcRenderer.send('changeWindow', 'max')
            } else {
                console.log('hide')
                ipcRenderer.send('changeWindow', 'hide')
            }
        }
    }
    render() {
        return (
            <div className="title-container">
                <div className="title" style={{ "WebkitAppRegion": "drag" }}>能夠拖拽的區域</div>
                <button onClick={this.handle('min')}>最小化</button>
                <button onClick={this.handle('max')}>最大化</button>
                <button onClick={this.handle('hide')}>托盤</button>
            </div>
        )
    }
}
  • 經過IPCRender與主進程通訊,控制窗口的顯示和隱藏

咱們一塊兒去dva中管理的model看看

  • home模塊
export default {
    namespace: 'home',
    state: {
        homes: [1, 2, 3],
        num: 0
    },
    reducers: {
        adds(state, { newNum }) {
            return {
                ...state,
                num: newNum
            }
        }
    },
    effects: {
        * add({ res, val }, { put, select, call }) {
            const { home } = yield select()
            console.log(home.num)
            yield console.log(res, val)
            const newNum = home.num + 1
            yield put({ type: 'adds', newNum })
        }
    },
}

dva真的能夠給咱們省掉不少不少代碼,並且更好維護,也更容易閱讀

  • 它的大概流程

clipboard.png

  • 若是不會的話建議去官網看例子,通常來講不會像RXJS學習路線那麼陡峭

Node.js中代碼

const express = require('express')
const { Server } = require("ws");
const app = express()
const wsServer = new Server({ port: 8080 })
wsServer.on('connection', (ws) => {
    ws.onopen = function () {
        console.log('open')
    }
    ws.onmessage = function (data) {
        console.log(data)
        ws.send('234')
        console.log('onmessage' + data)
    }
    ws.onerror = function () {
        console.log('onerror')
    }
    ws.onclose = function () {
        console.log('onclose')
    }
});

app.listen(8000, (err) => {
    if (!err) { console.log('監聽OK') } else {
        console.log('監聽失敗')
    }
})

上來先給一個websocket 8080端口監聽,綁定事件,而且使用express監聽原生端口8000

  • 這樣好處,一個應用並不必定所有須要實時通信,根據需求來決定何時進行實時通信
  • Restful架構依然存在,Node.js做爲中間件或者IO輸出比較多的底層服務器進行CRUD均可以

今天先寫到這裏,套路都同樣,基本的架子已經已經搭好,能夠把代碼clone下去慢慢玩,加功能。 能夠的話給個star和贊,謝謝

本文git倉庫源碼地址,歡迎star

相關文章
相關標籤/搜索