Electron 打包 React项目

Electron 打包 React项目

本篇内容将记录并介绍使用Electron来打包已有的React项目;

1、安装Electron

npm install -g electron
npm install -D electron
  • 我这里使用的是全局安装electron,原因是因为electron包比较大,而且运行Electron这一操作是可复用的,所以我认为全局安装electron更加合适,这里只需要安装一次electron,在哪里都能使用。

2、相关配置

  1. 在根目录添加 main.js文件

    // Modules to control application life and create native browser window
    const {app, BrowserWindow} = require('electron');
    const path = require('path');
    const url = require('url');
    
    // 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;
    
    function createWindow () {
      // Create the browser window.
      mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          preload: path.join(__dirname, 'preload.js'),
        },
      });
    
      // 加载应用----适用于 react 项目
     mainWindow.loadURL('http://localhost:3000/');
    
      // 打开开发者工具,默认不打开
      // mainWindow.webContents.openDevTools()
    
      // 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;
      });
    }
    
    // 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.
    
  2. 修改package.json配置

    • 将刚刚配置的main.js文件配置到package的”main”: “main.js”
    • 默认情况下,homepage 是 http://localhost:3000,build 后,所有资源文件路径都是 /static,而 Electron 调用的入口是 file :协议,/static 就会定位到根目录去,所以找不到静态文件。在 package.json 文件中添加 homepage 字段并设置为”.”后,静态文件的路径就变成了相对路径,就能正确地找到了添加如下配置:

      “homepage”:”.”

    • 配置

          {
            "name": "rui",
            "version": "0.0.1",
            "private": true,
            "main": "main.js",  // 配置启动文件
            "homepage": ".",
            "ruiPath": "packages",
            "workspaces": [
                "packages/*"
            ],
            "scripts": {
                "bootstrap": "yarn && lerna bootstrap",
                "start": "node scripts/start.js",
                "build": "node scripts/build.js",
                "test": "node scripts/test.js",
                "build:dll": "webpack --config ./config/webpack.dll.config.js",
                "electron:start": "electron .",
                "electron:build": "electron-packager ./build rui --platform=win32 --arch=x64 --out=./../out --app-version=0.0.1 --electron-version=6.0.1",
                "compile": "rollup -c rollup/rollup.config.js",
                "pub": "lerna publish"
            },
            "dependencies": {
                "@babel/core": "7.1.6",
                "@svgr/webpack": "2.4.1",
                "antd": "^3.20.0",
                "axios": "^0.19.0",
                "babel-core": "7.0.0-bridge.0",
                "babel-eslint": "9.0.0",
                "babel-jest": "23.6.0",
                "babel-loader": "8.0.4",
                "babel-plugin-named-asset-import": "^0.3.0",
                "babel-preset-react-app": "^7.0.0",
                "bfj": "6.1.1",
                "case-sensitive-paths-webpack-plugin": "2.1.2",
                "chalk": "^2.4.2",
                "classnames": "^2.2.6",
                "codemirror": "^5.48.0",
                "css-loader": "1.0.0",
                "dotenv": "6.0.0",
                "dotenv-expand": "4.2.0",
                "eslint": "5.6.0",
                "eslint-config-react-app": "^3.0.6",
                "eslint-loader": "2.1.1",
                "eslint-plugin-flowtype": "2.50.1",
                "eslint-plugin-import": "2.14.0",
                "eslint-plugin-jsx-a11y": "6.1.2",
                "eslint-plugin-react": "7.11.1",
                "file-loader": "2.0.0",
                "fork-ts-checker-webpack-plugin-alt": "0.4.14",
                "fs-extra": "7.0.0",
                "html-webpack-plugin": "4.0.0-alpha.2",
                "identity-obj-proxy": "3.0.0",
                "jest": "23.6.0",
                "jest-pnp-resolver": "1.0.1",
                "jest-resolve": "23.6.0",
                "jquery": "^3.4.1",
                "lodash": "^4.17.15",
                "lodash.debounce": "^4.0.8",
                "lodash.isequal": "^4.5.0",
                "mini-css-extract-plugin": "0.4.3",
                "optimize-css-assets-webpack-plugin": "5.0.1",
                "overlayscrollbars": "^1.8.0",
                "parse-json": "^5.0.0",
                "pnp-webpack-plugin": "1.1.0",
                "postcss-flexbugs-fixes": "4.1.0",
                "postcss-loader": "3.0.0",
                "postcss-preset-env": "6.3.1",
                "postcss-safe-parser": "4.0.1",
                "prop-types": "^15.7.2",
                "rc-editor-core": "^0.8.10",
                "react": "^16.7.0",
                "react-app-polyfill": "^0.2.0",
                "react-dev-utils": "^7.0.1",
                "react-document-title": "^2.0.3",
                "react-dom": "^16.7.0",
                "react-overlayscrollbars": "^0.2.1",
                "react-redux": "^7.1.0",
                "react-router-dom": "^5.0.1",
                "redux": "^4.0.1",
                "redux-thunk": "^2.3.0",
                "resolve": "^1.8.1",
                "sass-loader": "7.1.0",
                "style-loader": "0.23.0",
                "terser-webpack-plugin": "1.1.0",
                "url-loader": "1.1.1",
                "webpack": "4.19.1",
                "webpack-dev-server": "3.1.14",
                "webpack-manifest-plugin": "2.0.4",
                "workbox-webpack-plugin": "3.6.3"
            },
            "eslintConfig": {
                "extends": "react-app"
            },
            "browserslist": [
                ">0.2%",
                "not dead",
                "not ie <= 11",
                "not op_mini all"
            ],
            "jest": {
                "collectCoverageFrom": [
                    "src/**/*.{js,jsx,ts,tsx}",
                    "!src/**/*.d.ts"
                ],
                "resolver": "jest-pnp-resolver",
                "setupFiles": [
                    "react-app-polyfill/jsdom"
                ],
                "testMatch": [
                    "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
                    "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,ts,tsx}"
                ],
                "testEnvironment": "jsdom",
                "testURL": "http://localhost",
                "transform": {
                    "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
                    "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
                    "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
                },
                "transformIgnorePatterns": [
                    "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
                    "^.+\\.module\\.(css|sass|scss)$"
                ],
                "moduleNameMapper": {
                    "^react-native$": "react-native-web",
                    "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
                },
                "moduleFileExtensions": [
                    "web.js",
                    "js",
                    "web.ts",
                    "ts",
                    "web.tsx",
                    "tsx",
                    "json",
                    "web.jsx",
                    "jsx",
                    "node"
                ]
            },
            "babel": {
                "presets": [
                    "react-app"
                ]
            },
            "devDependencies": {
                "@babel/plugin-external-helpers": "^7.2.0",
                "@babel/preset-env": "^7.5.4",
                "@babel/preset-react": "^7.0.0",
                "electron": "^6.0.1",
                "electron-packager": "^14.0.4",
                "eslint-plugin-react-hooks": "^1.6.1",
                "gulp": "^4.0.2",
                "gulp-babel": "^8.0.0",
                "node-sass": "^4.12.0",
                "redux-devtools-extension": "^2.13.8",
                "require-uncached": "^2.0.0",
                "rollup": "^1.17.0",
                "rollup-plugin-babel": "^4.3.3",
                "rollup-plugin-clear": "^2.0.7",
                "rollup-plugin-commonjs": "^10.0.1",
                "rollup-plugin-json": "^4.0.0",
                "rollup-plugin-node-resolve": "^5.2.0",
                "rollup-plugin-postcss": "^2.0.3",
                "rollup-plugin-scss": "^1.0.1",
                "typescript": "^3.5.3",
                "webpack-cli": "^3.3.6",
                "webpack-merge": "^4.2.1"
            },
            "repository": {
                "type": "git",
                "url": "git@github.com:realRoyHsu/rui.git"
            }
        }
      
  3. 在根目录添加preload.js文件

        // All of the Node.js APIs are available in the preload process.
          // It has the same sandbox as a Chrome extension.
          window.addEventListener('DOMContentLoaded', () => {
            const replaceText = (selector, text) => {
              const element = document.getElementById(selector);
              if (element) element.innerText = text;
            };
    
            for (const type of ['chrome', 'node', 'electron']) {
              replaceText(`${type}-version`, process.versions[type]);
            }
          });
    

3、启动 Electron

# 启动react项目
npm start
# 启动electron
npm run electron:start

注意:启动electron应用后,如何无法显示index页面,可能是你路由配置了BrowserRouter模式,请改成HashRouter。VUE项目出不来的话,很大可能是使用了history路由模式,改成hash路由模式就可以了。

4、打包

  • 注意:要修改跟目录下面的main.js文件

    //   加载应用----react 打包
         mainWindow.loadURL(url.format({
             pathname: path.join(__dirname, './build/index.html'),
             protocol: 'file:',
             slashes: true,
         }));
    // 加载应用----适用于 react 开发配置
    // mainWindow.loadURL('http://localhost:3000/');
  • 将你配置的main.js、package.json、preload.js,复制一份到public静态文件中,不然打包后,还是会无法打开程序。
    注意:修改public中的main.js pathname: path.join(__dirname, './index.html')

    //   加载应用----react 打包
         mainWindow.loadURL(url.format({
             pathname: path.join(__dirname, './index.html'),
             protocol: 'file:',
             slashes: true,
         }));
    // 加载应用----适用于 react 开发配置
    // mainWindow.loadURL('http://localhost:3000/');
  • 安装electron-packager

    # 根目录下安装electron-packager包
    npm install electron-packager --save-dev
    # 安装electron-packager命令
    npm install electron-packager -g
  • electron-packager命令介绍

    electron-packager <location of project> <name of project> <platform> <architecture> <electron version> <optional options>
    • location of project: 项目的本地地址,此处我这边是 ~/knownsec-fed
    • location of project: 项目名称,此处是 knownsec-fed
    • platform: 打包成的平台
    • architecture: 使用 x86 还是 x64 还是两个架构都用
    • electron version: electron 的版本
  • 配置package.json打包脚本

    “electron:build”: “electron-packager ./build rui –platform=win32 –arch=x64 –out=./../out –ar –app-version=0.0.1 –electron-version=6.0.1”,

  • 开始打包

    先编译出静态资源
    npm run build
    在编译electron
    npm run electron:build

找到打包文件中exe文件,双击打开运行

5、asar压缩

"electron:build": "electron-packager ./build rui --platform=win32 --arch=x64 --out=./../out --app-version=0.0.1 --asar --electron-version=6.0.1",

6、使用inno来编译打包好的文件

    原文作者:Royal
    原文地址: https://segmentfault.com/a/1190000020020324
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞