Saltar al contenido principal

Instrucciones de Compilación

Follow the guidelines below for building Electron itself, for the purposes of creating custom Electron binaries. Para empaquetar y distribuir su código de aplicación con los binarios preconstruidos de Electron vea la guía distribución de aplicaciones.

Pre-requisitos de la Plataforma

Comprueba los pre-requisitos de tu plataforma para la compilación antes de avanzar

Herramientas de construcción

Electron's Build Tools automate much of the setup for compiling Electron from source with different configurations and build targets. Si deseas configurar el entorno de forma manual, las instrucciones se enumeran a continuación.

Electron usa gyp para la generación de proyectos y ninja para su compilación. Las configuraciones del Proyecto puede ser encontradas en los archivos .gn y .gni.

Archivos GN

Los siguientes archivos gn contienen las reglas principales para la construcción de Electron:

  • BUILD.gn define como Electron mismo es construido e incluye la configuraciones predeterminadas para enlazar con Chromium.
  • build/args/{testing,release,all}.gn contiene los argumentos por defecto para la construcción de Electron.

Pre-requisitos de GN

Necesitaras instalar depot_tools, el conjunto de herramientas usadas para consumir Chromium y sus dependencias.

Ademas, en Windows, tendrás que asignar la variable de ambiente DEPOT_TOOLS_WIN_TOOLCHAIN=0. Para hacerlo, abre Panel de ControlSistema y SeguridadSistemaOpciones de Configuración Avanzadas y agrega a tu sistema la variable de ambiente DEPOT_TOOLS_WIN_TOOLCHAIN con el valor 0. Esto le indica a depot_tools que utilice tu version instalada de Visual Studio (por defecto, depot_tools intentará descargar una version interna de Google, a la cual solo empleados de Google tienen acceso).

Configurar el cache de Git

Si planeas hacer checkout de Electron más de una vez (por ejemplo, para tener múltiples directorios paralelos verificados en diferentes ramas), el uso del cache git acelerará las llamadas posteriores a gclient. Para hacer esto, establezca una variable de entorno GIT_CACHE_PATH:

$ export GIT_CACHE_PATH="${HOME}/.git_cache"
$ mkdir -p "${GIT_CACHE_PATH}"
# Esto usará alrededor de 16G.

Obteniendo el código

$ 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.

En lugar de https://github.com/electron/electron, puedes usar tu propio fork aquí (algo como https://github.com/<username>/electron).

Una nota al tirar/empujar

Si usted tiene la intención de git pull or git push desde el repositorio oficial electron en el futuro, ahora necesita actualizar las URLs de la carpeta origin correspondiente.

$ 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 funciona verificando las dependencias en un archivo llamado DEPS dentro de la carpeta src/electron (tales como Chromium o Node.js). Ejecutar gclient sync -f asegura que todas las dependencias requeridas para compilar Electron coninciden con ese archivo.

Así que, para tirar, ejecutarías los siguientes comandos:

$ cd src/electron
$ git pull
$ gclient sync -f

Compilando

Set the environment variable for chromium build tools

On Linux & MacOS

$ cd src
$ export CHROMIUM_BUILDTOOLS_PATH=`pwd`/buildtools

On Windows:

# cmd
$ cd src
$ set CHROMIUM_BUILDTOOLS_PATH=%cd%\buildtools

# PowerShell
$ cd src
$ $env:CHROMIUM_BUILDTOOLS_PATH = "$(Get-Location)\buildtools"

To generate Testing build config of Electron:

On Linux & MacOS

$ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\")"

On Windows:

# cmd
$ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\")"

# PowerShell
gn gen out/Testing --args="import(\`"//electron/build/args/testing.gn\`")"

To generate Release build config of Electron:

On Linux & MacOS

$ gn gen out/Release --args="import(\"//electron/build/args/release.gn\")"

On Windows:

# cmd
$ gn gen out/Release --args="import(\"//electron/build/args/release.gn\")"

# PowerShell
$ 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.

Para la configuración de depuración:

$ ninja -C out/Testing electron

Para la configuración de la lanzamiento:

$ 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.

El ejecutable compilado estará en ./out/Testing:

$ ./out/Testing/Electron.app/Contents/MacOS/Electron
# or, on Windows
$ ./out/Testing/electron.exe
# or, on Linux
$ ./out/Testing/electron

Embalaje

En linux, primero elimine la información de depuración y de símbolos:

$ electron/script/strip-binaries.py -d out/Release

Para empaquetar la aplicación compilada electron como un archivo zip distribuible:

$ ninja -C out/Release electron:electron_dist_zip

Compilación cruzada

Para compilar una plataforma que no sea la misma que la que estás construyendo, establece los argumentos GN target_cpu y target_os. Por ejemplo, para compilar un objetivo x86 de un host x64, especificar target_cpu = "x86" en gn args.

$ gn gen out/Testing-x86 --args='... target_cpu = "x86"'

No todas las combinaciones de origen y destino sea CPU/SO son compatibles con Chromium.

HostObjetivoEstado
Windows x64Windows arm64Experimental
Windows x64Windows x86Automáticamente probado
Linux x64Linux x86Automáticamente probado

Si prueba otras combinaciones y las encuentra para funcionar, por favor actualice este documento :)

See the GN reference for allowable values of target_os and target_cpu.

Windows en Arm (experimental)

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

O (si usa PowerShell):

$env:ELECTRON_BUILDING_WOA=1
gclient sync -f --with_branch_heads --with_tags

Despues, corra gn gen como arriba con target_cpu="arm64".

Verificación

Para ejecutar las pruebas, primero deberás compilar los módulos de prueba en la misma versión de node.js en la que se creó el proceso de compilación. Para generar cabeceras de compilación para los módulos a compilar, ejecute lo siguiente en el directorio src/.

$ ninja -C out/Testing electron:node_headers

Ahora puede ejecutar run the tests.

Si estás depurando algo, puede ser de gran ayuda pasarle algunas banderas adicionales a el binario de Electron:

$ npm run test -- \
--enable-logging -g 'BrowserWindow module'

Compartir la caché git entre varias máquinas

Es posible compartir este directorio con otras máquinas exportándolo como SMB share en Linux, pero solo un proceso/máquina puede usar la memoria caché a la vez. Los bloqueos creados por el script git-cache intentarán evitar esto, pero puede que no funcione perfectamente en una red.

En Windows, SMBv2 tiene un caché de directorio que causará problemas con el script del git cache, por lo que es necesario desactivarlo configurando la clave de registro

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Lanmanworkstation\Parameters\DirectoryCacheLifetime

a cero. Para más información: https://stackoverflow.com/a/9935126

Esto puede establecerse rápidamente en powershell (ejecutado como administrador):

New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\Lanmanworkstation\Parameters" -Name DirectoryCacheLifetime -Value 0 -PropertyType DWORD -Force

Problemas

gclient sync se queja sobre rebase

Si gclient sync es interrumpido el arbol de git puede quedar en mal estado, lo que conduce a un mensaje críptico cuando se ejecuta gclient sync en el futuro:

2> Conflict while rebasing this branch.
2> Fix the conflict and run gclient again.
2> See man git-rebase for details.

Si no hay conflictos de git o rebases en src/electron, puede necesitar abortar un git am en 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.

Se me está pidiendo un nombre de usuario/contraseña para chromium-internal.googlesource.com

Si ve un prompt para Username for 'https://chrome-internal.googlesource.com': cuando corre gclient sync en Windows, es probable que la variable de entorno DEPOT_TOOLS_WIN_TOOLCHAIN no esta establecida a 0. Abra Control PanelSystem and SecuritySystemAdvanced system settings y agregue un variable de sistema DEPOT_TOOLS_WIN_TOOLCHAIN con valor 0. Esto le indica a depot_tools que utilice tu version instalada de Visual Studio (por defecto, depot_tools intentará descargar una version interna de Google, a la cual solo empleados de Google tienen acceso).

e Module not found

If e is not recognized despite running npm i -g @electron/build-tools, ie:

Error: Cannot find module '/Users/<user>/.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.