
What is Electron ?
Electron is framework to develop the native desktop application for all major platforms (windows, Mac and Linux) using HTML , CSS and Javascript.
How to Install Electron?
To install Electron , we need to install nodejs and npm . To check if NodeJs and npm are installed in the system , you can run the below commands in the command line
node -v
npm -v
Create directory where you will set up the electron project.
Cd myelectronproj
We’re going to run the npm init command to create a package.json, which will store our project settings and dependencies:
npm init -y
Note: The -y flag provides default options automatically
To install electron globally you can run the below command:
npm install electron -g
To install it as a development dependency in your app
npm install electron –save-dev –save-exact
Within your project folder, create a new file called main.js. After that open the package.json file and make a couple updates as shown below:
{
…..
“main”: “main.js”, // Make sure that is main.js
“scripts”: {
“start”: “electron .” // Update this
},
……….
}
The scripts property will allow us to run npm start in the console to launch our Electron app, instead of writing electron .
In the main.js , we have to copy and paste the below code:
const {app, BrowserWindow} = require(‘electron’)
const path = require(‘path’)
const url = require(‘url’)
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, ‘index.html’),
protocol: ‘file:’,
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on(‘closed’, () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
app.on(‘ready’, createWindow)
app.on(‘window-all-closed’, () => {
if (process.platform !== ‘darwin’) {
app.quit()
}
})
app.on(‘activate’, () => {
if (win === null) {
createWindow()
}
})
createWindow() function helps define the actual application window that will be loaded once a user runs the application.
window-all-closed calls app.quote() on non-mac operating systems.
activate calls createWindow() if win is null.
Create an index.html file and copy and paste the below code in that.
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<script>We are running Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
Run the following command to run the application
npm start