React uses Electron to develop the desktop

React is a popular JavaScript library for building web applications. Combined with the Electron framework, React applications can be easily packaged as desktop applications. Following are the steps to develop a desktop application using React and Electron:

1. Install Electron

First, you need to install Electron. Run the following command in a terminal:

npm install electron --save-dev

2. Create an Electron application

Using the CLI tools provided by Electron, you can create an Electron application. Run the following command in a terminal:

npx electron-forge init my-app

This will create an Electron application called my-app and generate some default files and directories.

3. Install React and related dependencies

In the Electron application directory, you need to install React. Run the following command in a terminal:

npm install react react-dom --save
npm install -D @babel/preset-react

Among them, @babel/preset-react is a Babel preset for converting JSX syntax into ordinary JavaScript code.

4. Create React components

Inside the src directory, create a React component called App.js. In components, you can build web interfaces using components and libraries provided by React. For example, you can use the Material-UI library to build a simple interface:

import React from 'react';
import {
    
     makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles({
    
    
  root: {
    
    
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '100vh',
  },
  button: {
    
    
    backgroundColor: '#3f51b5',
    color: 'white',
    fontWeight: 'bold',
    fontSize: '1.5rem',
    padding: '1rem 2rem',
  },
});

function App() {
    
    
  const classes = useStyles();

  return (
    <div className={
    
    classes.root}>
      <Button className={
    
    classes.button} variant="contained">
        Hello World
      </Button>
    </div>
  );
}

export default App;

5. Add webpack configuration

To be able to package React applications, you need to add Webpack configuration. In the root directory of your Electron application, create a file called webpack.config.js and enter the following code:

const path = require('path');

module.exports = {
    
    
  entry: './src/index.js',
  output: {
    
    
    filename: 'bundle.js',
    path: path.join(__dirname, 'dist'),
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
    
    
          loader: 'babel-loader',
          options: {
    
    
            presets: ['@babel/preset-env', '@babel/preset-react'],
          },
        },
      },
    ],
  },
};

In this code, entry specifies the entry file of the application, output specifies the packaged file name and path, and module.rules specifies Babel's conversion rules.

6. Modify the startup script

In order to start a React application, you need to modify the startup script of the Electron application. In the package.json file, modify the startup script to the following code:

"start": "webpack --mode development --watch & electron ."

This will use Webpack to package the React application as bundle.js and use Electron to start the application.

7. Rendering React components

In the main process of your Electron application, you need to use the API provided by Electron to render React components. In the main.js file, use the following code:

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

function createWindow() {
    
    
  const win = new BrowserWindow({
    
    
    width: 800,
    height: 600,
    webPreferences: {
    
    
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  win.loadFile('index.html');
}

app.whenReady().then(() => {
    
    
  createWindow();

  app.on('activate', () => {
    
    
    if (BrowserWindow.getAllWindows().length === 0) {
    
    
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
    
    
  if (process.platform !== 'darwin')    app.quit();
  }
});

In this code, the createWindow function creates an Electron window and loads the index.html file. You also need to inject React and ReactDOM libraries in the preload.js file:

window.React = require('react');
window.ReactDOM = require('react-dom');

8. Create HTML file

In the root directory of your Electron application, create a file called index.html and enter the following code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello Electron</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="./bundle.js"></script>
  </body>
</html>

In this file, you need to render the React component into a div element with id root.

9. Run the application

In a terminal, start the development server for the React application with the following command:

npm start

In another terminal, start the Electron application with the following command:

npm run electron

In this way, you can see the React component in the Electron window.

10. Packaging and distributing the application

When you're done developing, you need to package and publish your application. You can use the packaging tools provided by Electron, such as electron-packager and electron-builder, to package your application into an executable file. You can publish the executable to an app store or website so users can download and install it.

In conclusion, using React and Electron together to develop desktop applications can help you quickly build cross-platform applications and provide many powerful features. By building web interfaces with React, you can use familiar tools and techniques to build applications. If you want to build a desktop application, React and Electron might be a good choice.

Guess you like

Origin blog.csdn.net/ZTAHNG/article/details/131123165