- In the project folder, run
npm init
on command line. - In the
package.json
file, themain
field should bemain.js
. - Run
npm install electron --save-dev
- Don't forget to add the
.gitignore
file to avoid commiting thenode_modules
folder. - In
package.json
file, underscripts
add"start": "electron .",
- Add your
index.html
file - Add your
main.js
file that loads theindex.html
file when the app starts.
To start the app, run npm run start
.
- Add a new
preload.js
script that exposes selected properties of Electron'sprocess.versions
object to the renderer process in aversions
global variable: - To attach this script to your renderer process, pass its path to the
webPreferences.preload
option in the BrowserWindow constructor: - Create a
renderer.js
script that uses thedocument.getElementById
DOM API to replace the displayed text for the HTML element withinfo
as itsid
property: - modify your
index.html
by adding a new element withinfo
as itsid
property, and attach yourrenderer.js
script.
main.js
code:
const { app, BrowserWindow } = require('electron')
const path = require('path')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
preload.js
code:
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('versions', {
node: () => process.versions.node,
chrome: () => process.versions.chrome,
electron: () => process.versions.electron
})
index.js
code:
<script src="./renderer.js"></script>
renderer.js
code:
const information = document.getElementById('info')
information.innerText = `This app is using Chrome (v${window.versions.chrome()}), Node.js (v${window.versions.node()}), and Electron (v${window.versions.electron()})`
- Add conversion script by running:
npm install --save-dev @electron-forge/cli
npx electron-forge import
- Check
package.json
file to see if indevDependencies
there arestart
,package
,make
added underscripts
.
To create a distributable, run npm run make
.
Create a file named forge.config.js
with the following code:
For MacOS:
module.exports = {
packagerConfig: {
osxSign: {},
// ...
osxNotarize: {
tool: 'notarytool',
appleId: process.env.APPLE_ID,
appleIdPassword: process.env.APPLE_PASSWORD,
teamId: process.env.APPLE_TEAM_ID
}
// ...
}
}
For Windows:
module.exports = {
// ...
makers: [
{
name: '@electron-forge/maker-squirrel',
config: {
certificateFile: './cert.pfx',
certificatePassword: process.env.CERTIFICATE_PASSWORD
}
}
]
// ...
}