Introduction
Electron is a framework that allows you to create native desktop applications using web technologies such as JavaScript, HTML and CSS. In this tutorial, we'll build a simple notes application that can be used on Linux, MacOS, and Windows.
Prerequisites
Have Node.js and npm installed. If you don't already have them, download and install from https://nodejs.org/.
Initial configuration
Create a new folder for your project and navigate inside:
mkdir electron-notes-app && cd electron-notes-app
Initialize a new npm project:
npm init -y
Install Electron
npm install electron --save-dev
Creation of the project structure
Create the following files and folders:
main.js
(the main file of the Electron app)index.html
(the app UI)styles.css
(app styles)
Structuring of the user interface
In the index.html
file, enter the following code:
<!DOCTYPE html>
<html>
<head>
<title>Electron Notes App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<textarea id="noteContent"></textarea>
<button id="saveBtn">Salva Nota</button>
</div>
<script src="renderer.js"></script>
</body>
</html>
In styles.css
, add some basic styles:
.container {
padding: 20px;
display: flex;
flex-direction: column;
height: 100vh;
}
textarea {
flex: 1;
margin-bottom: 10px;
}
button {
align-self: flex-end;
}
Electron logic
In main.js
, add:
const { app, BrowserWindow } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform!== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Application logic
Create a renderer.js
file and add:
const fs = require('fs');
document.getElementById('saveBtn').addEventListener('click', () => {
const content = document.getElementById('noteContent').value;
fs.writeFileSync('nota.txt', content);
alert('Nota salvata con successo!');
});
This code will save the contents of the textarea to a file called nota.txt
each time the button is pressed.
Launch the application
In the package.json
file, edit the "scripts" section to include:
"start": "electron main.js"
Now you can start the application with:
npm start
Conclusion
You've created a notes application with Electron that runs on Linux, MacOS, and Windows. You can further expand this app by adding features such as managing multiple notes, implementing a database, or integrating with cloud services.