With the development of JavaScript open source community, the application scenarios of JavaScript are more and more extensive. So far, JavaScript can be competent in Web development, desktop development, APP development and server-side development.
In terms of desktop development, Electron is my personal favorite solution, based on HTML, CSS, JavaScript, and cross-platform. A lot of great desktop software has been developed using Electron: Checklists
Electron case
Electron case
(yes, Microsoft’s VSCode was also developed at Electron, and Microsoft didn’t use their own kit, so the Electron desktop solution should be excellent.)
Create a simple desktop application
The prerequisite is that NodeJS must be installed in the development environment
- Install the Electron
npm install electron -g
- Create a directory and prerequisite files
mkdir hello-world && cd hello-world
touch main.js && touch package.json && touch index.html
- Write to package.json file
{" name ":" your - app ", "version" : "0.1.0 from", "main" : ". The main js "}Copy the code
- Write to the main.js file
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 win function createWindow () { // Create the browser window. win = new BrowserWindow({width: 800, height: 600}) // and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // 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. win = 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', () => { // 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', () => { // 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 (win === 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.Copy the code
- Write to index.html
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World! </title> </head> <body> <h1>Hello World! </h1> We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>. </body> </html>Copy the code
-
Run electron at the terminal.
-
You can see a desktop application
The first application
Electron details can be found in the official documentation
Create a React project
Creating a desktop application with Electron is easy, but using HTML+Javascript will definitely require some front-end libraries to aid development.
The mainstream front-end libraries include vue. JS, AngularJS and ReactJS. All three libraries/frameworks are good, but I chose React.
React creating a project is tedious because it uses JSX and requires configuring Babel, Webpack or Browserify
Create React App creates React projects quickly and easily, and provides a hot debugging environment. Refer to official documentation for details
Simply put, the Create React App creates a React project template, configuration, and handy script commands for debugging and deploying the React front end.
NPM start enables http://localhost:3000/ hot debugging for projects created using the Create React App. Compile all files by NPM run build in the build directory under the root directory.
Integrate Electron and React
The project created by the Create React App is a pure front-end project, integrating the React project and Electron while preserving hot debugging and local package references requires the following simple operations
- You need to create the Electron startup file main.js in the root of the React project (not the SRC directory).
- Add main to package.json file in React project with value “./main.js”
- Change win.loadURL in main.js to
win.loadURL(url.format({
pathname: path.join(__dirname, './build/index.html'),
protocol: 'file:',
slashes: true
}))
Copy the code
So far, run electron in the root directory to launch the desktop application created by React.
But there are a few problems
- The resource file cannot be displayed, and an error message is displayed indicating that the file cannot be found in the debugging panel
- Every time
npm run build
Then you can see the modified item - System package cannot be obtained, for example, system cpus information cannot be obtained with os.cpus().
A few small steps are needed to solve these problems
-
Json to add the field “homepage”:”.” By default, homepage is http://localhost:3000. After build, all files in homepage will be/static, and the Electron entry will be file: Protocol, /staitc will locate to the root directory of the system, so no static files can be found. After adding the homepage field to the package.json file and setting it to “.”, the static file path becomes a relative path and can be found correctly.
-
Change the main.js startup page to http://localhost:3000/
win.loadURL('http://localhost:3000/')
Copy the code
At development time, after starting nom Start, launch Electron on another terminal. This will allow for thermal debugging in electron
Json, set the DEV field to true/false, and then change main.js to the following:
Const PKG = require('./package.json') // reference package.json // check whether it is development mode if(pkg.dev){win.loadurl ("http://localhost:3000/") }else{ win.loadURL(url.format({ pathname: path.join(__dirname, './build/index.html'), protocol: 'file:', slashes: true })) }Copy the code
In the future, change DEV to true/false as needed before running electron
Finally, if you cannot call the local package through require by running either index.html or http://localhost:3000 in your build, you need to use window.require.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
var os = window.require('os') // not be : var os = require('os')
console.log("got:",os.cpus())
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
</div>
CPU count: {os.cpus().length}
</div>
);
}
}
export default App;
Copy the code
Using the require
Paste_Image.png
Using the window. The require
Paste_Image.png
This works regardless of whether the launch page is http://localhost:3000/ or build/index.html.
At this point, the Electron and React integration is complete. Most of the work is done using the tools provided by the React and Electron officials to generate the project, and only a few configuration and entry files need to be modified.
To summarize
- Create a React project with create-react-app
- Create the Electron entry file main.js in the root directory and modify the startup page of main.js
- In package.json, add the main field to “main.js”, add the homepage field to “.”, and add the DEV field to true/false (DEV is optional, if you prefer to modify mian.js).
- Apply the local library to use window.require instead of require
Welcome everyone Jane book or my personal blog to communicate with me