Electron-builder transforms web projcets into distributable desktop installation packages, addressing the limitation of standalone executables that require specific folder contexts to run. This approach enhances portability for end-users.
1. Configure npm Mirrors
Set up mirrors too accelerate downloads in environments with network constraints:
npm config set electron_mirror https://npm.taobao.org/mirrors/electron/
npm config set electron-builder-binaries_mirror https://npm.taobao.org/mirrors/electron-builder-binaries/
2. Create the Main Process File (main.js)
Define the application entry point to manage windows and integrate a local server for static assets:
const { app, BrowserWindow, Menu } = require('electron');
const path = require('path');
const httpServer = require('http-server');
function initializeAppWindow() {
const appWindow = new BrowserWindow({
width: 1024,
height: 768,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
Menu.setApplicationMenu(null);
appWindow.loadFile('dist/index.html');
httpServer.createServer({ root: './dist' }).listen(8080);
}
app.whenReady().then(() => {
initializeAppWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) initializeAppWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
3. Configure package.json
Specify build settings and dependencies for electron-builder:
{
"name": "desktop-app",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron .",
"package": "electron-builder"
},
"build": {
"productName": "MyDesktopApp",
"appId": "com.example.myapp",
"directories": {
"output": "installers"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"installerIcon": "assets/icon.ico",
"uninstallerIcon": "assets/icon.ico",
"createDesktopShortcut": true,
"createStartMenuShortcut": true,
"shortcutName": "MyDesktopApp"
},
"win": {
"target": ["nsis", "zip"]
},
"files": ["dist/**/*", "main.js"]
},
"dependencies": {
"http-server": "^14.1.1"
}
}
Key configuration fields include:
productName: Application name used in the installer.appId: Unique identifier following reverse domain notation.nsis: Windows installer options for customization.files: Specifies which directories and files to include in the build.
4. Generate the Installer
Execute the build command to produce the installation package:
npm run package
The resulting executable (e.g., MyDesktopApp Setup 1.0.0.exe) can be distributed for installation on Windows systems.