preface

Recently, I have been using TrTC-electronic-SDK of Tencent Cloud to develop cross-platform desktop video conferencing software, so I plan to use Electron to build the development environment.

In the company network, the installation is smooth, but to the home remote development, because there is no agent, only in the installation link encountered a lot of problems, although each is a small problem, but one after another, also let head big. Presumably other beginners who are not using proxies will encounter these problems as well.

Therefore, I decided to include the problems encountered in the installation, operation and packaging process of Electron, on the one hand, it is convenient for me to check in the future, and on the other hand, I hope to help fellow passers-by. If you have any mistakes, please leave a message.

Keyword Description

Project directory

The outermost package.json directory in the project is represented as [Project directory] below.

Application path

The resulting program root or app package, as in this example:

  • MAC: [project directory]/bin/mac/xxxxxxx.app, (this path can be accessed directly using the CD command).

  • Win: [project directory]/bin/win-unpacked

[Application path] is used in the following sections.

Problems encountered during installation

Problem 1: The Electron download is slow or even stuck

When downloading tmp-3320-1-shasums256.txt-6.1.9 or other files, it may be very slow, even after a long wait for NPM Timeout error:

Downloading tMP-3320-1-shasums256.txt -6.1.9 [=>] Downloading tMP-3320-1-shasums256.txt -6.1.9 [=>] Downloading 1.0% of 5.56 kB (0 B/s)Copy the code

Problem analysis

When no proxy is configured, the NPM fails to access foreign resources at a very low speed or even times out due to the export restriction of the network operator. Is it ok to configure the proxy? Neither, because even though we have configured the proxy address for NPM, the Electron installation script still downloads the installation package through IP, so the proxy can only speed up NPM, but not the Electron download.

The solution

  • Plan A

    If you are working from home, you can switch to the national NPM mirror:

#Specifies the NPM domestic mirror
$ npm config set registry=https://registry.npm.taobao.org/
#Specify the domestic mirror address for Electron
$ npm config set ELECTRON_MIRROR=https://npm.taobao.org/mirrors/electron/ 
$ npm install
Copy the code
  • Plan BIf you work at a company, your company’s network administrator may already have a proxy set up, and you need to verify that the NPM proxy configuration points to the company’s proxy server and that environment variables are configuredELECTRON_GET_USE_PROXY, if none is configured, perform the following steps:
  1. To set up the NPM agent:NPM config set all_proxy=[your proxy address].
  2. configurationELECTRON_GET_USE_PROXYEnvironment variables so that Electron’s installation script will be downloaded through NPM’s agent.

If you are in a Mac environment:

$ export ELECTRON_GET_USE_PROXY=true
Copy the code

If you are in Windows, right click “[Computer] > [Properties] > [Advanced System Settings] > [Environment Variables]”, please click the following figure:

  1. performnpm installNPM install --proxy=[your proxy address].

Problem 2: ERROR 404 occurred when downloading Electron

Problem analysis

After the NPM image address is changed, the download path of resources is changed.

We can see that above 404 error in the address is: http://npm.taobao.org/mirrors/electron/v8.1.1/electron-v8.1.1-darwin-x64.zip.

But in fact is the official source installed in the address: http://mirrors.npmjs.org/electron/8.1.1/electron-v8.1.1-darwin-x64.zip.

A closer look reveals that the version number in the official address does not contain the letter “V”, and that the script still spells out a path with V8.1.1 during installation.

The solution

Enter the following command on the terminal:

$ npm config setElectron_custom_dir 8.1.1It depends on the version number
Copy the code

Other Installation problems

Collected some user feedback, found that they encountered different problems, not all covered in this chapter. If you encounter an installation problem that is not listed in this chapter, or if you have failed to solve the problem by following the above solution, you are recommended to refer to the appendix: Manual Offline Installation Electron section.

Problems encountered at runtime

Fault 1: The message “Electron failed to install correctly” is displayed on the terminal.

When the installation appears to be complete and the project is running, the following error appears on the terminal:

Error: Electron failed to install correctly, please delete node_modules/electron and try installing again
Copy the code

Problem analysis

The installation process seems to complete quickly without any errors, but in fact the Electron installation fails and only the node_modules/ Electron directory is generated. The files in the directory are incomplete and the “path.txt” in the script does not exist, causing an exception to be thrown at runtime.

Switch to node_modules/electron and run NPM run postinstall. It turned out that there was a 404 problem during the download, but NPM install was executed in the root directory of the project without giving an error or terminating the installation process. Instead, a subsequent installation continued, giving the illusion that the installation was complete.

The solution

Please read the first half of the article mentioned in the installation of possible problems, and according to the plan in the article for troubleshooting. If the problem persists, you can follow the following three steps to download it manually:

  1. performnpm config get cacheView the cache directory.
  2. Download Electron manually and place it in the cache directory.
  3. To performnpm install.

Problem 2: Crash when calling camera or microphone

When trTC-electronic-SDK starts the camera and microphone, the program crashes directly:

Problem analysis

This problem occurs on new macs upgraded to MAC 10.15. Because MAC 10.15 has protection enabled by default, the Electron process started by vscode has no access to the camera and microphone, so the Electron process crashes.

The solution

  • Option A: Run the project using an authorized terminal.
  • Option B: authorize vscode: choose system preferences > security and privacy to authorize vscode.
  • Plan C: Perform the following steps to disable the protection mechanism:
    1. Restart the system and hold down command + R until the system enters protected mode.
    2. Open terminal inputcsrutil disableDisable the protection mechanism.
    3. Restart, enter the system normally, and you can start the project using vscode terminal.
    4. To restart the protection mechanism, perform only step 2csrutil enable.

Problem 3: The Electron error “XX is not defined” is reported in the console.

When running the project, Electron prompts in the console that XX is not defined, where xx refers to the Node module.

Such as:

Uncaught ReferenceError: require is not defined
Copy the code

Problem analysis

Since Electron starts from 5.0, the default value of the nodeIntegration configuration item changes from true to false. As a result, node modules such as require and PATH are not supported by default.

The solution

Change the nodeIntegration configuration item to true in the Electron main.js file:

  let win = new BrowserWindow({
    width: 1366.height: 1024.webPreferences: {
      nodeIntegration: true.// Set this to true}});Copy the code

Problems with packing

Problem 1: The. Node module is loaded incorrectly

When the packaged compiled program runs, the console will see a similar error message:

  • NodeRTCCloud is not a constructor

  • Cannot open xxx/trtc_electron_sdk.node

  • dlopen(xxx/trtc_electron_sdk.node, 1): image not found

If information similar to the above is displayed, the trTC_electron_sdK. node module is not properly packaged into the program.

Problem analysis

For your convenience, we need to explain the concept of **[working path]** :

When the Electron application is running, the global.process.cwd() function is called and the result “/” is the runtime working path. When loading files at runtime, the first “/” used starts from the current working path.

When we write the build configuration, naturally will use “/” as [application path], “/” at run time, however, is the representative of a path [work], [work path] and [] application path, file loading is the root cause of the failure, the following lists the two paths in the relationship between different platform runtime:

  • Mac environment: / points to [app path]/Contents/Frameworks.

  • Windows: / points to [application path].

So, when we build code for different platforms, we also need to tell programs to load files in different directories.

In addition, there are two issues to pay attention to:

  • Trtc-electronic-sdk. node is a. Node module that needs to be packaged with a native ext-Loader plug-in or other plug-ins with similar functions.

  • Win environment: trTC_electron_sdK. node also depends on.dll and.lib files in the same directory, which need to be packaged together, as shown below:

The solution

Step 1: Install native- Ext-Loader

 $ npm i native-ext-loader -D
Copy the code

Step 2: Modify the WebPack configuration:

 module: {
     rules: [{test: /\.node$/.loader: 'native-ext-loader'.options: { 
           rewritePath: os.platform() === 'win32' ? './resources' : '.. /Resources']}}},Copy the code
  • usevue-cliCreate the project where the WebPack configuration is storedvue.config.jsIn the fileconfigureWebpackIn the options.
  • usecreate-react-appCreate the project, webPack configuration file as[project directory] / node_modules/react - scripts/config/webpack config. Js

Step 3: Modify the build option in package.json (case sensitive) in the electron Builder package configuration:

"Build ": {" omit ": "..." , "win": { "extraFiles": [ { "from": "node_modules/trtc-electron-sdk/build/Release/", "to": "./resources", "filter": ["**/*"] } ] }, "mac": { "extraFiles": [ { "from": "node_modules/trtc-electron-sdk/build/Release/trtc_electron_sdk.node", "to": "./Resources" } ] }, "directories": { "output": "./bin" } },Copy the code

Problem 2: The entry file cannot be found

A project created using create-react-app may encounter this problem when packaged using electron Builder:

$node_modules\.bin\electron-builder. CMD • electron- Builder version=22.6.0 OS =6.1.7601 • Loaded Configuration file=package.json ("build"Field) • public/electron.js not found. Please see https://medium.com/@kitze/%EF%B8%8F-from-react-to-an-electron-app-ready-for-production-a0468ECB1DA3 • Loaded parent configuration = React-CRaCopy the code

Public /electron.js not found public/electron.js not found

Problem analysis

When packing react applications, the electron Builder will fix public/electron. Js as the electron entry file, Ignores main.electron. Js configured with the main option in package.json. For more information, please refer to the url given in the error message, or click here.

The solution

  1. Move and rename entry file:
$ cd$mv main.electron.js./public/electron.jsCopy the code
  1. Modify pacakge.json file:
{
  "main": "public/electron.js"."Omission": "..."
}
Copy the code

Problem 3: syntax error in fS-extra module

The following error occurred while packing:

\node_modules\electron- Builder \node_modules\fs-extra\lib\empty\index.js:33} catch {^ SyntaxError: Unexpected token { at new Script (vm.js:51:7)Copy the code

Problem analysis

Try {/**/} catch {/**/} catch {/**/}

The solution

To upgrade to the latest node, see nodeJS official website.

Appendix: Manually and offline install the Electron

It has been proved that manual installation can bypass network problems. Both iMac and Windows can follow this step to complete the installation. Step by step, please read.

Operating train of thought

  1. Download the Electron compression package in advance.
  2. If the Electron download is slow or a timeout error occurs, the installation process is interrupted.
  3. Modify the Electron installation script to remove the download process and decompress the downloaded compressed package.
  4. Run the installation script for Electron to complete the installation.

The preparatory work

  • You are advised to install the latest nodeJS. For details about how to install nodeJS, see nodeJS official website.
  • In this paperElectron - v8.1.1 - win32 - x64. ZipFor example, select other operating systems based on actual conditions.
  • In this paper, CMDER and Windows Terminal are used for operation and verification. If you use DOS operation, please replace some instructions with valid DOS instructions by yourself, such as:mvReplace withmove.

Step 1: Download the Electron installation package in advance

  1. Open the Release page of the Electorn warehouse in your browser: github.com/electron/el…

  2. Obtain the required version and the compressed package matching the operating system from the list. The following uses the microelectron v8.1.1 in 64-bit Windows as an example:

  3. Click on the electron-v8.1.1-win32-x64.zip file to download to the project directory.

The download process takes some time. While waiting for the download, perform other steps.

Step 2: Add the Electron configuration and install

Edit package.json and add “electron”: “8.1.1” to the child of devDependencies.

"DevDependencies ": {"devDependencies": , "electron" : "8.1.1}"Copy the code

After editing, save and exit, execute under [project directory] :

$ npm install
Copy the code

Step 3: Interrupt the Electron installation process

During the installation process of Electron, the following two situations will occur on the terminal if nothing goes wrong:

Case 1: Installation progress is extremely slow:

Downloading tMP-3320-1-shasums256.txt -6.1.9 [=>] Downloading tMP-3320-1-shasums256.txt -6.1.9 [=>] Downloading 1.0% of 5.56 kB (0 B/s)Copy the code

Case 2: ETIMEOUT error:

$ npm install
#Omit...
>[email protected] postinstall [project directory]\node_modules\electron
> node install.js(node:7208) UnhandledPromiseRejectionWarning: RequestError: Connect ETIMEDOUT 52.216.240.76:443 at ClientRequest.<anonymous> ([project directory]\node_modules\@electron\get\node_modules\got\source\ request-as-Event-emitters. Js :178:14)#Omit...
Copy the code

52.216.240.76:443 (dynamic) is not the address of the NPM image, but the web service that is located outside the country, and direct access will be very slow.

You need to pressctrl+cInterrupt the installation process and start manual installation.

Step 4: Modify the Electron installation script and perform the installation

  1. Confirm the download in step 1 (# Step 1: Download the Electron installation package in advance)Electron - v8.1.1 - win32 - x64. ZipWhether the file is complete, if the download is complete, then move it to[Project directory]/node_modules/electronDirectory:
$Mv [project directory]/electron-v8.1.1-win32-x64.zip node_modules/electron
Copy the code
  1. Enter the[Project directory]/node_modules/electronDirectory, openinstall.jsThe file, around line 30, can be found with the following code:
downloadArtifact({
version,
artifactName: 'electron'.force: process.env.force_no_cache === 'true'.cacheRoot: process.env.electron_config_cache,
platform: process.env.npm_config_platform || process.platform,
arch: process.env.npm_config_arch || process.arch
}).then((zipPath) = > extractFile(zipPath)).catch((err) = > onerror(err))
Copy the code

The function of this code is: download the Electron compression package, after downloading the extractFile method to decompress to the current directory.

Now you need to change it to: directly unzip the electron-v8.1.1-win32-x64.zip file from the current directory to the current directory.

  1. Comment out the downloaded code and add the unzipped code:
extractFile('electron - v8.1.1 win32 - x64.zip');
// downloadArtifact({
// version,
// artifactName: 'electron',
// force: process.env.force_no_cache === 'true',
// cacheRoot: process.env.electron_config_cache,
// platform: process.env.npm_config_platform || process.platform,
// arch: process.env.npm_config_arch || process.arch
// }).then((zipPath) => extractFile(zipPath)).catch((err) => onerror(err))
Copy the code
  1. Start executing the installation script:
$ node install.js
Copy the code

If the installation is successful, there is no output on the terminal. The process is quick and can be completed in seconds.

Step 5: Run Electron

Go back to [Project directory] and run Electron. If the following information is displayed and the default UI of Electron is displayed, the installation is successful:

$ cd. /.. /
$ node_modules/.bin/electron

A path to an Electron app may be specified. It must be one of the following:
  - index.js file.
  - Folder containing a package.json file.
  - Folder containing an index.js file.
  - .html/.htm file.
  - http://, https://, or file:// URL.

Options:
  -i, --interactive     Open a REPL to the main process.
  -r, --require         Module to preload (option can be repeated).
  -v, --version         Print the version.
  -a, --abi             Print the Node ABI version.
Copy the code