- Инструкции по сборке
- Системные требования
- Build Tools
- GN Files
- Требования для GN
- Setting up the git cache
- Получение кода
- A note on pulling/pushing
- Сборка
- Упаковка
- Кросс-компиляция
- Windows на Arm (экспериментально)
- Тестирование
- Sharing the git cache between multiple machines
- Устранение проблем
- gclient sync complains about rebase
- I’m being asked for a username/password for chromium-internal.googlesource.com
- e Module not found
- electron-builder ¶
- Installation¶
- Note for PNPM¶
- Note for Yarn 3¶
- Boilerplates¶
- Quick Setup Guide¶
- Programmatic Usage¶
- Pack Only in a Distributable Format¶
- Debug¶
Инструкции по сборке
Follow the guidelines below for building Electron itself, for the purposes of creating custom Electron binaries. For bundling and distributing your app code with the prebuilt Electron binaries, see the application distribution guide.
Системные требования
Перед началом проверьте требования сборки для вашей системы
Build Tools
Electron’s Build Tools automate much of the setup for compiling Electron from source with different configurations and build targets. If you wish to set up the environment manually, the instructions are listed below.
Electron uses GN for project generation and ninja for building. Project configurations can be found in the .gn and .gni files.
GN Files
The following gn files contain the main rules for building Electron:
- BUILD.gn defines how Electron itself is built and includes the default configurations for linking with Chromium.
- build/args/.gn contain the default build arguments for building Electron.
Требования для GN
Вам нужно будет установить depot_tools , набор инструментов, используемый для извлечения Chromium и его зависимостей.
Также, для Windows вам потребуется добавить переменную среды DEPOT_TOOLS_WIN_TOOLCHAIN=0 . Чтобы это сделать, откройте Панель управления → Система и безопасность → Система → Дополнительные параметры системы и добавьте системную переменную DEPOT_TOOLS_WIN_TOOLCHAIN со значением 0 . Она говорит depot_tools использовать вашу локальную версию Visual Studio (по умолчанию, depot_tools попробует загрузить приватную Google версию к которой имеют доступ только Гугловцы).
Setting up the git cache
If you plan on checking out Electron more than once (for example, to have multiple parallel directories checked out to different branches), using the git cache will speed up subsequent calls to gclient . To do this, set a GIT_CACHE_PATH environment variable:
$ export GIT_CACHE_PATH="$/.git_cache" $ mkdir -p "$" # Это будет использовать примерно 16 гигабайт.
Получение кода
$ mkdir electron && cd electron $ gclient config --name "src/electron" --unmanaged https://github.com/electron/electron $ gclient sync --with_branch_heads --with_tags # This will take a while, go get a coffee.
Вместо https://github.com/electron/electron , вы можете использовать здесь свой собственный форк (что-то вроде https://github.com//electron ).
A note on pulling/pushing
If you intend to git pull or git push from the official electron repository in the future, you now need to update the respective folder’s origin URLs.
$ cd src/electron $ git remote remove origin $ git remote add origin https://github.com/electron/electron $ git checkout main $ git branch --set-upstream-to=origin/main $ cd -
📝 gclient works by checking a file called DEPS inside the src/electron folder for dependencies (like Chromium or Node.js). Running gclient sync -f ensures that all dependencies required to build Electron match that file.
So, in order to pull, you’d run the following commands:
$ cd src/electron $ git pull $ gclient sync -f
Сборка
Set the environment variable for chromium build tools
$ cd src $ export CHROMIUM_BUILDTOOLS_PATH=`pwd`/buildtools
$ cd src $ set CHROMIUM_BUILDTOOLS_PATH=%cd%\buildtools
To generate Testing build config of Electron:
$ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\")"
To generate Release build config of Electron:
$ gn gen out/Release --args="import(\"//electron/build/args/release.gn\")"
Note: This will generate a out/Testing or out/Release build directory under src/ with the testing or release build depending upon the configuration passed above. You can replace Testing|Release with another names, but it should be a subdirectory of out .
Also you shouldn’t have to run gn gen again—if you want to change the build arguments, you can run gn args out/Testing to bring up an editor. To see the list of available build configuration options, run gn args out/Testing —list .
To build, run ninja with the electron target: Note: This will also take a while and probably heat up your lap.
Для конфигурации тестирования:
$ ninja -C out/Testing electron
$ ninja -C out/Release electron
This will build all of what was previously ‘libchromiumcontent’ (i.e. the content/ directory of chromium and its dependencies, incl. Blink and V8), so it will take a while.
Собранный исполняемый файл будет находиться в ./out/Testing :
$ ./out/Testing/Electron.app/Contents/MacOS/Electron # или, на Windows $ ./out/Testing/electron.exe # или, на Linux $ ./out/Testing/electron
Упаковка
On linux, first strip the debugging and symbol information:
$ electron/script/strip-binaries.py -d out/Release
To package the electron build as a distributable zip file:
$ ninja -C out/Release electron:electron_dist_zip
Кросс-компиляция
To compile for a platform that isn’t the same as the one you’re building on, set the target_cpu and target_os GN arguments. For example, to compile an x86 target from an x64 host, specify target_cpu = «x86» in gn args .
$ gn gen out/Testing-x86 --args='. target_cpu = "x86"'
Not all combinations of source and target CPU/OS are supported by Chromium.
Host | Target | Состояние |
---|---|---|
Windows x64 | Windows arm64 | Experimental |
Windows x64 | Windows x86 | Автоматически тестировано |
Linux x64 | Linux x86 | Автоматически тестировано |
If you test other combinations and find them to work, please update this document 🙂
See the GN reference for allowable values of target_os and target_cpu .
Windows на Arm (экспериментально)
To cross-compile for Windows on Arm, follow Chromium’s guide to get the necessary dependencies, SDK and libraries, then build with ELECTRON_BUILDING_WOA=1 in your environment before running gclient sync .
set ELECTRON_BUILDING_WOA=1 gclient sync -f --with_branch_heads --with_tags
Или (если используется PowerShell):
$env:ELECTRON_BUILDING_WOA=1 gclient sync -f --with_branch_heads --with_tags
Далее, запустите gn gen , как указано выше, с target_cpu=»arm64″ .
Тестирование
To run the tests, you’ll first need to build the test modules against the same version of Node.js that was built as part of the build process. To generate build headers for the modules to compile against, run the following under src/ directory.
$ ninja -C out/Testing third_party/electron_node:headers
Если вы что-то отлаживаете, то вам может быть полезно передать некоторые дополнительные флаги в бинарный Electron:
$ npm run test -- \ --enable-logging -g 'BrowserWindow module'
Sharing the git cache between multiple machines
It is possible to share the gclient git cache with other machines by exporting it as SMB share on linux, but only one process/machine can be using the cache at a time. Блокировки, установленные скриптом git-cache попытаются предотвратить это, однако возможна нестабильная работа по сети.
На Windows, у SMBv2 есть кэш директорий, который будет создавать проблемы со скриптом git-cache, поэтому необходимо отключить его, установив ключ регистра
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Lanmanworkstation\Parameters\DirectoryCacheLifetime
Это можно быстро установить в powershell (запускается от имени администратора):
New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\Lanmanworkstation\Parameters" -Name DirectoryCacheLifetime -Value 0 -PropertyType DWORD -Force
Устранение проблем
gclient sync complains about rebase
If gclient sync is interrupted the git tree may be left in a bad state, leading to a cryptic message when running gclient sync in the future:
2> Conflict while rebasing this branch. 2> Fix the conflict and run gclient again. 2> See man git-rebase for details.
If there are no git conflicts or rebases in src/electron , you may need to abort a git am in src :
$ cd ../ $ git am --abort $ cd electron $ gclient sync -f
This may also happen if you have checked out a branch (as opposed to having a detached head) in electron/src/ or some other dependency’s repository. If that is the case, a git checkout —detach HEAD in the appropriate repository should do the trick.
I’m being asked for a username/password for chromium-internal.googlesource.com
Если вы видите запрос для Имя пользователя для ‘https://chrome-internal.googlesource.com’: при запуске gclient sync на Windows, это возможно, потому что DEPOT_TOOLS_WIN_TOOLCHAIN переменная окружения не установлена в 0. Откройте Панель управления → Система и безопасность → Система → Дополнительные параметры системы и добавьте системную переменную DEPOT_TOOLS_WIN_TOOLCHAIN с значением 0 . Она говорит depot_tools использовать вашу локальную версию Visual Studio (по умолчанию, depot_tools попробует загрузить приватную Google версию к которой имеют доступ только Гугловцы).
e Module not found
If e is not recognized despite running npm i -g @electron/build-tools , ie:
Error: Cannot find module '/Users//.electron_build_tools/src/e'
We recommend installing Node through nvm. This allows for easier Node version management, and is often a fix for missing e modules.
electron-builder ¶
A complete solution to package and build a ready for distribution Electron app for macOS, Windows and Linux with “auto update” support out of the box.
- NPM packages management:
- Native application dependencies compilation (including Yarn support).
- Development dependencies are never included. You don’t need to ignore them explicitly.
- Two package.json structure is supported, but you are not forced to use it even if you have native production dependencies.
- All platforms: 7z , zip , tar.xz , tar.lz , tar.gz , tar.bz2 , dir (unpacked directory).
- macOS: dmg , pkg , mas , mas-dev .
- Linux: AppImage, snap, debian package ( deb ), rpm , freebsd , pacman , p5p , apk .
- Windows: nsis (Installer), nsis-web (Web installer), portable (portable app without installation), AppX (Windows Store), Squirrel.Windows.
- Pack in a distributable format already packaged app.
- Separate build steps.
- Build and publish in parallel, using hard links on CI server to reduce IO and disk space usage.
- electron-compile support (compile for release-time on the fly on build).
Installation¶
Yarn is strongly recommended instead of npm.
yarn add electron-builder —dev
Note for PNPM¶
In order to use with pnpm , you’ll need to adjust your .npmrc to use any one the following approaches in order for your dependencies to be bundled correctly (ref: #6389):
Note: Setting shamefully-hoist to true is the same as setting public-hoist-pattern to *.
Note for Yarn 3¶
Yarn 3 use PnP by default, but electron-builder still need node-modules(ref: yarnpkg/berry#4804). Add configuration in the .yarnrc.yaml as follows:
Boilerplates¶
- electron-webpack-quick-start — A bare minimum project structure to get started developing with electron-webpack. Recommended.
- electron-react-boilerplate A boilerplate for scalable cross-platform desktop apps.
- electron-react-redux-boilerplate A minimal boilerplate to get started with Electron, React and Redux.
- electron-boilerplate A minimalistic yet comprehensive boilerplate application.
- Vue CLI 3 plugin for Electron A Vue CLI 3 plugin for Electron with no required configuration.
- electron-vue-vite A real simple Electron + Vue3 + Vite2 boilerplate.
- vite-electron-builder Secure boilerplate for Electron app based on Vite. TypeScript + Vue/React/Angular/Svelte/Vanilla
Quick Setup Guide¶
electron-webpack-quick-start is a recommended way to create a new Electron application.
- Specify the standard fields in the application package.json — name, description , version and author.
- Specify the build configuration in the package.json as follows:
"build": "appId": "your.id", "mac": "category": "your.app.category.type" > >
"scripts": "pack": "electron-builder --dir", "dist": "electron-builder" >
Please note that everything is packaged into an asar archive by default.
For an app that will be shipped to production, you should sign your application. See Where to buy code signing certificates.
Programmatic Usage¶
See node_modules/electron-builder/out/index.d.ts . Typings for TypeScript are provided and also can be found here.
Code snippit provided below is also shown “in action” here as well.
"use strict" const builder = require("electron-builder") const Platform = builder.Platform // Promise is returned builder.build( targets: Platform.MAC.createTarget(), config: "//": "build options, see https://goo.gl/QQXmcV" > >) .then(() => // handle result >) .catch((error) => // handle error >)
Pack Only in a Distributable Format¶
You can use electron-builder only to pack your electron app in a AppImage, Snaps, Debian package, NSIS, macOS installer component package ( pkg ) and other distributable formats.
./node_modules/.bin/electron-builder --prepackaged
—projectDir (the path to project directory) option also can be useful.
Debug¶
Set the DEBUG environment variable to debug what electron-builder is doing:
FPM_DEBUG env to add more details about building linux targets (except snap and appimage).
On Windows the environment variable is set using the set command.
PowerShell uses different syntax to set environment variables.