Why is 💡 a free trial version?

The environment of paid reading, on the one hand, well protects the intellectual property rights of creators, on the other hand, improves the writing motivation and content quality of creators.

My article is divided into “free version” and “paid version”. The “free version” is mainly short and quick daily experience skills and technology sharing, while the “paid version” is longer, more systematic and more detailed.

Regardless of the “free version” and “paid version”, I am carefully prepared, repeatedly verified and proofread, to ensure the quality of the content, adhere to the original.

If you are interested in the “free trial version”, please follow the author’s wechat official account “Sleeping plum and Smelling Flowers” to read the paid article.

❤️ Original writing is not easy, your support is the greatest support for the author to encourage ❤️

🌷🌷—— Try read Start —— port 🌷 port

Electron is a technology framework for building cross-platform applications using HTML, CSS, and JavaScript based on Chromium and Node.js, compatible with Mac, Windows, and Linux. Although B/S is the mainstream of current development, C/S still has a large market demand. Limited by the sandbox of the browser, Web applications cannot meet the requirements in some scenarios, while desktop applications can read and write local files and invoke more system resources. In addition, with the advantages of low cost and high efficiency of Web development, this method is becoming more and more popular among developers. This article focuses on how to setup a desktop client development project using Electron and create-React-app. Don’t miss the React Tech Stack

Table of Contents – Sneak peek

Let’s take a look at what’s included in this share:

1 introduction

2. Foundation construction

  • 2.1 Creating a standardized React Project

  • 2.2 Streamlining Projects

  • 2.3 exposed webpack

  • 2.4 support Sass/Less/Stylus

3 Integration with Ant Design

  • 3.1 Installing Ant Design

  • 3.2 Antd loading on demand

  • 3.3 Customize Antd theme colors

4 integrated Electron

  • 4.1 Accelerating the Electron Installation through domestic Mirrors

  • 4.2 Accelerating the Installation of Electron through cache

  • 4.3 Electron configuration

  • 4.4 Enabling the Electron Dev Hot Update Mode

5 Achieve recursive traversal of files in the folder

  • 5.1 Main process development

  • 5.2 Rendering process development

  • 5.3 Viewing preliminary Results

  • 5.4 Render lists using Antd

6 pack Electron

  • 6.1 installation electron – builder

  • 6.2 configuration electron – builder

  • 6.3 Disabling map File Generation

  • 6.4 Configuring the Release Version Main Entrance

  • 6.5 Build Electron Application

  • 6.6 Setting icon of the Development Environment

  • 6.7 Setting the Build Icon

7 Other common configurations

  • 7.1 APP Window Size

  • 7.2 Canceling the Cross-domain Restriction

  • 7.3 Canceling the menu bar

1 introduction

At present, front-end projects in the industry are mainly developed based on Vue and React. When I used Vue to do a project before, I published “Hand in hand To Teach you to Develop cross-platform desktop Application using Electron5+ VUE-CLI3” on our official account “Wo Mei Wo Wen Hua” in July 2019. The front end technology is moving so fast. After more than a year, Vue3.0 has been released. Electron has been updated to version 10. I also moved to the React technology stack. In the previous development projects using Electron+Vue, vuE-CLI-plugin-electron-Builder was used, which was really convenient.

Github.com/nklayman/vu…

However, in the face of such a fast update pace of Electron, relying on third-party tools often cannot use the latest version of Electron. Rather than expect third-party tools to update every day, build your own. Therefore, after moving to React, I decided to build the Electron+CRA standard development environment by myself instead of using project templates like Electron – React – Boilerplate. On the one hand, components can be updated more freely and project architecture can be formulated. On the other hand, Electron can be used more deeply to improve the technical level.

Does note:

CRA in this article stands for create-react-app

At the beginning of each line in the code area:

“+” indicates new data

“-” indicates deletion

“M” indicates modification

Through this article you can grasp:

  1. Standardization project was set up using Electron+CRA+Antd.
  2. Through the implementation of all the files in the local directory Demo, master the ability to develop local applications based on Electron.
  3. Use electron builder to pack Windows and MAC installation packages.

The main version used in this article:

  1. Node. Js 12.19.0
  2. The react 16.14.0
  3. Antd 4.7.2
  4. Electron 10.1.4

2. Foundation construction

2.1 Creating a standardized React Project

Execute the command. Create a standard CRA project:

npx create-react-app electron-cra
Copy the code

2.2 Streamlining Projects

Next, simplify the project by removing files that are not used in the general project.

├ ─ / node_modules ├ ─ package. Json ├ ─ / public | ├ ─ the favicon. Ico | ├ ─ index. The HTML - | ├ ─ logo192. PNG - | ├ ─ logo512. PNG - | ├ ─ mainfest. Json - | └ ─ robots. TXT ├ ─ README. Md ├ ─ / SRC - | ├ ─ App. CSS | ├ ─ App. Js - | ├ ─ App. Test, js - | ├ ─ index. The CSS - | ├ ─ index. Js - | ├ ─ logo. The SVG - | ├ ─ serviceWorker. Js - | └ ─ setupTests. Js └ ─ yarn. The lockCopy the code

The deleted directory structure is much cleaner:

├ ─ / node_modules ├ ─ / public | ├ ─ the favicon. Ico | ├ ─ index. The HTML ├ ─ / SRC | ├ ─ App. Js | └ ─ index. The js ├ ─ package. The json ├ ─ The README. Md └ ─ yarn. The lockCopy the code

Modify the following files one by one:

src/App.js

import React from 'react'

function App() {
    return (
        <div className="App">
            <h1>This is Electron CRA App.</h1>
        </div>
    )
}

export default App
Copy the code

src/index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(
    <App />,
    document.getElementById('root')
)
Copy the code

public/index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta  name="viewport" content="width=device-width, initial-scale=1" /> <title>Electron CRA</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html>Copy the code

The running effect is as follows:

After a cut clean, really happy.

2.3 exposed webpack

Create-react-app does not expose configuration files by default. To configure projects flexibly, you need to expose configuration files.

Create-react-app 2.0+ supports SASS itself, and eject is intended to support less, Stylus, and subsequent integration with Antd and load on demand. If you don’t need it, you don’t need eject.

Run the following command to expose the configuration file:

※ Note: The operation of exposing configuration files is irreversible!

Perform:

yarn eject
Copy the code

If you have not committed git before, you may get the following error:

Remove untracked files, stash or commit any changes, and try again
Copy the code

You need to execute it in the project root directory first, and submit git:

Git add. Git commit -mCopy the code

Wait a moment, eject succeeds and the directory changes as follows:

+ ├ ─ / config + | ├ ─ / jest + | ├ ─ env. Js + | ├ ─ getHttpsConfig. Js + | ├ ─ modules. Js + | ├ ─ paths. Js + | ├ ─ pnpTs. Js + | ├ ─ webpack. Config. Js < -- -- webpack configuration file + | └ ─ webpackDevServer. Config. Js ├ ─ / node_modules ├ ─ / public | ├ ─ the favicon. Ico | └ ─ Index.html + ├ ─ / scripts + | ├ ─ build. Js + | ├ ─ start. Js + | └ ─ test. The js ├ ─ / SRC | ├ ─ / common < - global public directory | ├ ─ Public module component/components < - directory | ├ ─ / pages < - page components directory | ├ ─ App. Js < - project main module | └ ─ index. The js < - project entry documents ├ ─ package. The json ├ ─ The README. Md └ ─ yarn. The lockCopy the code

After eject completes, run the project again and check whether it succeeded:

yarn start
Copy the code

Potholes:

The best way to install dependency packages is to run the yarn command. If CNPM install is used, an error may occur after eject yarn start:

Cannot find module ‘babel-loader’

There is also the possibility of various other packages being lost, so don’t use CNPM anyway.

2.4 support Sass/Less/Stylus

React supports Stylus, Sass, Less, and Stylus with Stylus CSS.

Before starting, review the yarn and NPM commands:

NPM command The corresponding yarn command
npm init yarn init
npm install yarn
npm install xxx –save yarn add xxx
npm install xxx –save-dev yarn add xxx –dev
npm install xxx –global yarn global add xxx
npm uninstall xxx –save yarn remove xxx
npm update –save yarn upgrade

Against 2.4.1 support Sass/Scss

After eject, although there is sass code in package.json and webpack.config.js, to use sass /Scss correctly, node-sass needs to be installed again.

Run the following command:

yarn add node-sass --dev
Copy the code

After the installation, the project supports Sass/Scss.

2.4.2 support Less

Install Less and less-loader:

yarn add less less-loader --dev
Copy the code

Then modify config/webpack.config.js:

// style files regexes const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/; + const lessRegex = /\.less$/; + const lessModuleRegex = /\.module\.less$/; . // Opt-in support for SASS (using.scss or.sass extensions). // By default we support SASS Modules with the // extensions .module.scss or .module.sass { test: sassRegex, exclude: sassModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction && shouldUseSourceMap, }, 'sass-loader' ), // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this  when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, }, // Adds support for CSS Modules, but using SASS // using the extension .module.scss or .module.sass { test: sassModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction && shouldUseSourceMap, modules: {getLocalIdent: getCSSModuleLocalIdent,},}, 'pass-loader'),}, + // exclude: lessModuleRegex, + use: getStyleLoaders( + { + importLoaders: 3, + sourceMap: isEnvProduction && shouldUseSourceMap, + }, + 'less-loader' + ), + sideEffects: true, + }, + { + test: lessModuleRegex, + use: getStyleLoaders( + { + importLoaders: 3, + sourceMap: isEnvProduction && shouldUseSourceMap, + modules: { + getLocalIdent: getCSSModuleLocalIdent, + }, + }, + 'less-loader' + ),Copy the code

After the preceding operations, the project supports less.

2.4.3 support Stylus

Support Stylus exactly the same as Less, first install Stylus and stylus-loader:

Run the following command:

yarn add stylus stylus-loader --dev
Copy the code

Once the installation is complete, modify config/webpack.config.js as described in the previous section to support less:

// style files regexes const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/; const lessRegex = /\.less$/; const lessModuleRegex = /\.module\.less$/; + const stylusRegex = /\.styl$/; + const stylusModuleRegex = /\.module\.styl$/; . + // Support stylus + {+ test: stylusRegex, + exclude: stylusModuleRegex, + use: getStyleLoaders(+ {+ importLoaders: 3, + sourceMap: isEnvProduction && shouldUseSourceMap, + }, + 'stylus-loader' + ), + sideEffects: true, + }, + { + test: stylusModuleRegex, + use: getStyleLoaders( + { + importLoaders: 3, + sourceMap: isEnvProduction && shouldUseSourceMap, + modules: { + getLocalIdent: getCSSModuleLocalIdent, + }, + }, + 'stylus-loader' + ),Copy the code

When finished, restart the project and the imported Stylus file can parse properly now.

3 Integration with Ant Design

Ant Design is a very useful front-end UI library that has been used in many projects.

Ant Design website: Ant. Design /index-cn

3.1 Installing Ant Design

Perform:

yarn add antd
Copy the code

3.2 Antd loading on demand

Ant Design has many styles, but only a few of them may be used in a project, so there is no need to load them all. On-demand loading of styles can be implemented using babel-plugin-import.

Install Babel – plugin – import:

yarn add babel-plugin-import --dev
Copy the code

Modify the package. The json:

    "babel": {
        "presets": [
            "react-app"
        ],
+       "plugins": [
+           [
+               "import",
+               {
+                   "libraryName": "antd",
+                   "style": "css"
+               }
+           ]
+       ]
    }
Copy the code

Then modify SRC/app.js to verify Antd:

	import React from 'react'
+	import { Button } from 'antd'
	import './style.styl'
	
	function App() {
	    return (
	        <div className="App">
	            <h1>This is Electron CRA App.</h1>
+	            <Button type="primary">Button</Button>
	        </div>
	    )
	}
	
	export default App
Copy the code

You can see that Antd’s Button component displays normally and Antd’s page reset style is in effect.

3.3 Customize Antd theme colors

Antd styles use Less as the development language. If you want to customize Ant Design theme colors, you need to have your project support Less (described in section 2.4.2).

Modify the config/webpack. Config. Js:

if (preProcessor) { + let preProcessorOptions = { + sourceMap: True, +} + if (preProcessor === "less-loader") {+ preProcessorOptions = {+ sourceMap: true, + // Custom theme + lessOptions: {+ modifyVars: {+ 'primary-color':' #ce9b13', // customize the global primary color, javascript: true, + }, + } + } loaders.push( { loader: require.resolve('resolve-url-loader'), options: { sourceMap: isEnvProduction && shouldUseSourceMap, }, }, { loader: require.resolve(preProcessor), M options: preProcessorOptions } ); }Copy the code

If your less version is lower, an error may be reported

options has an unknown property 'javascriptEnabled'. These properties are valid: object { lessOptions? , prependData? , appendData? , sourceMap? }Copy the code

Solution Upgrade the less and less-Loader versions or configure the less version based on the requirements of the current less version. You can move modifyVars and javascriptEnabled to the lessOptions level and remove lessOptions.

For more theme color configuration, please refer to Antd official website:

Ant. The design/docs/react /…

At this point, the Web version architecture of the project is complete. Let’s move on to Electron.

4 integrated Electron

If you have a scientific connection and a fast connection, installing Electron is very convenient. Run the following command to install:

yarn add electron --dev
Copy the code

Electron is relatively large, but there are a few other ways to speed up the download if it can’t be scientifically connected.

4.1 Accelerating the Electron Installation through domestic Mirrors

Change the YARN source to the Domestic Taobao image.

yarn config set registry https://registry.npm.taobao.org/
yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/
Copy the code

Then install electron:

yarn add electron --dev
Copy the code

4.2 Accelerating the Installation of Electron through cache

According to the official instruction of Electron, the core file downloaded by Electron will be stored in the cache. The next time we download it, we will check whether it has been downloaded. If it has been downloaded, we will not download it again.

Electron official note: github.com/electron/ge…

So we can go to Taobao mirror and download the required files by ourselves:

Npm.taobao.org/mirrors/ele…

For writing this article, the Electron version is 10.4.1 on macOS, so download the following two files:

  1. Electron – v10.1.4 – Darwin – x64. Zip
  2. SHASUMS256.txt

If Windows is used, perform the preceding steps to download the corresponding file.

Then create a folder for each downloaded file, named according to the spec Electron website.

If the YARN source has been changed to taobao image, the folder name is download address of the file without the colon and slash (add v before the version number)+ file name.

Then place it in the cache directory. The corresponding Electron cache directory for each system is as follows:

Linux: $XDG_CACHE_HOME or ~ / cache/electron/MacOS: ~ / Library/Caches/electron/Windows: $LOCALAPPDATA/electron/Cache or ~ / AppData/Local/electron/Cache /Copy the code

4.2.1 MacOC Cache Mode

Download file address:

https://npm.taobao.org/mirrors/electron/10.1.4/electron-v10.1.4-darwin-x64.zip
https://npm.taobao.org/mirrors/electron/10.1.4/SHASUMS256.txt
Copy the code

The name of the directory is:

Httpsnpm.taobao.org mirrorselectronv10.1.4 electron - v10.1.4 - Darwin - x64. Zip Httpsnpm.taobao.org mirrorselectronv10.1.4 SHASUMS256. TXTCopy the code

The file storage location is:

~ / Library/Caches/electron/httpsnpm.taobao.org mirrorselectronv10.1.4 electron - v10.1.4 - Darwin - x64. Zip/electron - v10.1.4 - darw The in - x64.zip ~ / Library/Caches/electron/httpsnpm.taobao.org mirrorselectronv10.1.4 SHASUMS256. TXT/SHASUMS256. TXTCopy the code

Similarly, if you have not changed to Taobao image and still use the default Settings, electron will download from GitHub and its folder name is:

Httpsgithub.com electronelectronreleasesdownloadv10.1.4 electron - v10.1.4 - Darwin - x64. Zip Httpsgithub.com electronelectronreleasesdownloadv10.1.4 SHASUMS256Copy the code

Then execute the install command to quickly complete the installation:

yarn add electron --dev
Copy the code

4.2.2 Windows Cache Mode

Download file address:

https://npm.taobao.org/mirrors/electron/10.1.4/electron-v10.1.4-win32-x64.zip
https://npm.taobao.org/mirrors/electron/10.1.4/SHASUMS256.txt
Copy the code

The name of the directory is:

Httpsnpm.taobao.org mirrorselectronv10.1.4 electron - v10.1.4 - win32 - x64. Zip Httpsnpm.taobao.org mirrorselectronv10.1.4 SHASUMS256. TXTCopy the code

The file storage location is:

C: \ Users \ your system user name \ AppData\Local\electron\Cache\httpsnpm.taobao.org mirrorselectronv10.1.4 electron - v10.1.4 - win32 - x64. Zip \ el Ectron - v10.1.4 - win32 - x64. Zip C: \ Users \ your system user name \ AppData\Local\electron\Cache\httpsnpm.taobao.org mirrorselectronv10.1.4 SHASUMS256. TXT \ SHASUMS256 TXTCopy the code

Then execute the install command to quickly complete the installation:

yarn add electron --dev
Copy the code

4.3 Electron configuration

Modify package.json by configuring the import file:

🌷🌷—— 🌷🌷 end

If you are interested in this sharing, please follow my wechat official account “Sleeping mei and Smelling Flowers” and continue to read “Super Details! Take you step by step to Build the Electronic 10+React16+Antd4 Architecture Project”.

🎈 Follow-up wonderful chapters – End of trial reading

4.3 Electron configuration

4.4 Enabling the Electron Dev Hot Update Mode

5 Achieve recursive traversal of files in the folder

5.1 Main process development

5.2 Rendering process development

5.3 Viewing preliminary Results

5.4 Render lists using Antd

6 pack Electron

6.1 installation electron – builder

6.2 configuration electron – builder

6.3 Disabling map File Generation

6.4 Configuring the Release Version Main Entrance

6.5 Build Electron Application

6.6 Setting icon of the Development Environment

6.7 Setting the Build Icon

7 Other common configurations

7.1 APP Window Size

7.2 Canceling the Cross-domain Restriction

7.3 Canceling the menu bar

8 epilogue

This post is a long one, and I spent a lot of time on Windows and MacOS. I hope it can save you a lot of exploring time.

If you are interested in this sharing, please follow my wechat official account “Sleeping mei and Smelling Flowers” and continue to read “Super Details! Take you step by step to Build the Electronic 10+React16+Antd4 Architecture Project”.