解决 Electron + React 白屏

问题

今天尝试用Electron+React开发一个简单的本地应用的界面, 按照教程搭建脚手架之后, 在浏览器中可以在http://localhost:3000/正常访问React。

而按理说在main.js文件里可以通过如下方法使Electron打开React运行的网址。

mainWindow.loadURL("http://localhost:3000");

然而Electron界面一直是白屏:

Electron控制台中输出:

<html lang="en"><head>
    <meta charset="utf-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#000000">
    <meta name="description" content="Web site created using create-react-app">
    <link rel="apple-touch-icon" href="/logo192.png">
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json">
    <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  <script defer="" src="/static/js/bundle.js"></script></head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  
</body></html>

按理说Electron应该是这样的:


解决方法

最后发现是脚手架搭建错误。应按照如下顺序搭建:

# 确保已安装 Node
# 安装 create-react-app 这个脚手架到全局
npm install -g create-react-app

# 生成项目工程文件夹
# 此工程会出现在运行此命令的路径下
create-react-app <项目名>

# 进入项目文件夹
cd <项目名>

# 运行React
npm start

# 不要停止上一条命令, 另开一个终端
# 在项目中安装Electron
# 特别注意, 这条命令可能会卡住一段时间不动, 需要耐心等待运行结束
npm i electron --save-dev

# 安装Devtron插件, 用于Debug
npm i devtron --save-dev

随后修改package.json文件:

// "version": "0.1.0",
// "private": true,
在此处添加:
"main": "main.js",
// "homepage": ".",
// "scripts": {
//     "start": "react-scripts start",
//     "build": "react-scripts build",
//     "test": "react-scripts test",
//     "eject": "react-scripts eject",
在此处添加:
"electron": "electron ."
// },

随后在与package.json相同的路径下添加main.js, 这是Electron的开发文件:

// 引入electron并创建一个BrowserWindow
const {app, BrowserWindow} = require('electron')
const isDev = require('electron-is-dev')
// 保持window对象的全局引用,避免JavaScript对象被垃圾回收时,窗口被自动关闭.
let mainWindow

function createWindow() {
    //创建浏览器窗口,宽高自定义具体大小你开心就好
    mainWindow = new BrowserWindow({
        width: 1024,
        height: 680,
        webPreferences: {
            nodeIntegration: true,
        }
    });
    // 开发时, 加载 react 界面
    mainWindow.loadURL("http://localhost:3000");
    // 打包后, 改为加载文件
    // mainWindow.loadURL(path.join('file://', __dirname, '/build/index.html'));
    // 打开开发者工具栏,默认不打开
    mainWindow.webContents.openDevTools();
    // 关闭window时触发下列事件.
    mainWindow.on('closed', function () {
        mainWindow = null
    });
}

app.on('ready', () => {
    createWindow();
});
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') {
        app.quit()
    }
});
app.on('activate', function () {
    if (mainWindow === null) {
        createWindow()
    }
});

以上。


运行

之后项目的启动顺序:

# 运行React
npm start

# 另开一个终端, 启动Electron
npm run electron

也有插件可以把两条命令合并起来运行, 这里不做介绍。

之后项目正常打开。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个简单的 Electron React 项目实例: 1. 创建一个新的项目文件夹并进入该文件夹: ``` mkdir electron-react-app cd electron-react-app ``` 2. 初始化 npm 项目: ``` npm init -y ``` 3. 安装必要的依赖项: ``` npm install --save electron react react-dom npm install --save-dev electron-builder babel-cli babel-preset-env babel-preset-react webpack webpack-cli webpack-dev-server html-webpack-plugin ``` 4. 创建一个 webpack 配置文件 webpack.config.js: ``` const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.join(__dirname, '/dist'), filename: 'index_bundle.js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['env', 'react'] } } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] }; ``` 5. 创建一个 .babelrc 配置文件: ``` { "presets": ["env", "react"] } ``` 6. 创建一个入口文件 src/index.js: ``` import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<h1>Hello, Electron and React!</h1>, document.getElementById('root')); ``` 7. 创建一个 HTML 文件 src/index.html: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Electron React App</title> </head> <body> <div id="root"></div> <script src="index_bundle.js"></script> </body> </html> ``` 8. 创建一个 main.js 文件作为 Electron 主进程文件: ``` const { app, BrowserWindow } = require('electron'); const path = require('path'); const url = require('url'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600 }); mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'dist', 'index.html'), protocol: 'file:', slashes: true })); mainWindow.on('closed', function () { mainWindow = null }); } app.on('ready', createWindow); app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit() } }); app.on('activate', function () { if (mainWindow === null) { createWindow() } }); ``` 9. 在 package.json 中添加以下脚本: ``` "scripts": { "start": "webpack-dev-server --mode development", "build": "webpack --mode production && electron-builder", "electron": "electron ." } ``` 10. 启动项目: ``` npm start ``` 这将启动 Webpack Dev Server 并在浏览器中打开应用程序。在开发期间,每当更改 React 代码时,Webpack Dev Server 会自动重新编译代码并重新加载应用程序。 11. 打包应用程序: ``` npm run build ``` 这将使用 Webpack 和 electron-builder 打包应用程序。打包后的应用程序将在 dist 目录中生成。 12. 运行应用程序: ``` npm run electron ``` 这将启动 Electron 并加载打包后的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值