Closed psmuler closed 1 year ago
Electronを使用してアプリを開発するには、まずNode.jsとnpm(Node Package Manager)がインストールされていることを確認してください。その後、以下の手順でプロジェクトを初期化できます。
mkdir my-electron-app
cd my-electron-app
package.json
ファイルの初期化:
npmを使ってプロジェクトを初期化し、package.json
ファイルを生成します。npm init
プロンプトに従ってプロジェクト情報を入力します。特にentry point
については、Electronアプリのメインファイル名(通常はmain.js
またはindex.js
)を指定してください。
npm install electron --save-dev
main.js
)をプロジェクトルートに作成します。このファイルには、Electronアプリの起動とウィンドウの作成に関するコードが入ります。main.js
の例:
const { app, BrowserWindow } = require('electron');
function createWindow() {
const 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();
}
});
index.html
ファイルの作成:
プロジェクトルートにindex.html
ファイルを作成し、アプリのUIを定義します。index.html
の例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
</body>
</html>
package.json
ファイルに起動スクリプトを追加:
package.json
ファイルのscripts
セクションに、アプリを起動するスクリプトを追加します。"scripts": {
"start": "electron ."
},
npm start
これで、Electronでコードされたアプリの開
画面に"File"と書かれたボタンを用意し、押されたらローカルから読み込むファイルを選択するためのポップアップを表示しましょう。
Electronアプリで「File」と書かれたボタンを作成し、クリックするとファイルを選択するためのポップアップが表示されるようにするには、以下の手順を実行してください。
index.html
ファイルにボタンを追加:index.html
ファイルに、"File"というテキストが表示されたボタンを追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
<button id="file-btn">File</button>
<script src="renderer.js"></script>
</body>
</html>
renderer.js
ファイルの作成:プロジェクトルートにrenderer.js
というファイルを作成し、以下のコードを追加します。このファイルでは、ボタンがクリックされたときのイベントリスナーを定義します。
const { ipcRenderer } = require('electron');
const fileBtn = document.getElementById('file-btn');
fileBtn.addEventListener('click', () => {
ipcRenderer.send('open-file-dialog');
});
main.js
ファイルの更新:main.js
ファイルに、ipcMain
を使用して、renderer.js
からのメッセージを受信し、ファイルダイアログを開くコードを追加します。
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: 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();
}
});
ipcMain.on('open-file-dialog', (event) => {
const options = {
title: 'Select a file',
properties: ['openFile'],
};
dialog.showOpenDialog(null, options).then((result) => {
if (!result.canceled) {
console.log('Selected file:', result.filePaths[0]);
}
});
});
以下のコマンドでElectronアプリを起動します。
npm start
これで、「File」と書かれたボタンが表示され、クリックするとファイル選択ポップアップが表示されるようになります。選択したファイルのパスは、main.js
内のconsole.log
で表示されます。
簡単なテキストエディタを導入し、先ほど読み込んだ.md形式ファイルを表示しましょう。変更を加えた後の保存機能もつけてください。以下コード内で変更がない点は必ず省略してください。
簡単なテキストエディタを作成し、.md形式のファイルを開いて表示し、変更を加えて保存できるようにするには、以下の手順を実行してください。
index.html
ファイルを更新:テキストエディタ用の<textarea>
要素と、"Save"ボタンを追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>My Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
<button id="file-btn">Open</button>
<button id="save-btn">Save</button>
<br />
<textarea id="text-editor" rows="20" cols="80"></textarea>
<script src="renderer.js"></script>
</body>
</html>
renderer.js
ファイルを更新:ファイルを開いてテキストエディタに表示する処理と、変更を加えた後の保存機能を追加します。
const { ipcRenderer } = require('electron');
const fs = require('fs');
const fileBtn = document.getElementById('file-btn');
const saveBtn = document.getElementById('save-btn');
const textEditor = document.getElementById('text-editor');
let currentFilePath = null;
fileBtn.addEventListener('click', () => {
ipcRenderer.send('open-file-dialog');
});
saveBtn.addEventListener('click', () => {
if (currentFilePath) {
saveFile(currentFilePath);
} else {
ipcRenderer.send('save-file-dialog');
}
});
ipcRenderer.on('selected-file', (event, filePath) => {
currentFilePath = filePath;
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
console.error(err);
return;
}
textEditor.value = data;
});
});
ipcRenderer.on('selected-save-path', (event, savePath) => {
currentFilePath = savePath;
saveFile(currentFilePath);
});
function saveFile(filePath) {
const content = textEditor.value;
fs.writeFile(filePath, content, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File saved:', filePath);
});
}
main.js
ファイルを更新:ファイルダイアログで選択したファイルをrenderer.js
に送信し、保存ダイアログを表示するコードを追加します。
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
// ... (createWindow, app.whenReady, app.onのコードは省略) ...
ipcMain.on('open-file-dialog', (event) => {
const options = {
title: 'Select a file',
properties: ['openFile'],
filters: [{ name: 'Markdown', extensions: ['md'] }],
};
dialog.showOpenDialog(null, options).then((result) => {
if (!result.canceled) {
const filePath = result.filePaths[0];
event.sender.send('selected-file', filePath);
}
});
});
ipcMain.on('save-file-dialog', (event) => {
const options = {
title: 'Save file',
filters: [{ name: 'Markdown', extensions: ['md'] }],
};
dialog.showSaveDialog(null, options).then((result) => {
if (!result.canceled) {
const savePath = result.filePath;
event.sender.send('selected-save-path', savePath);
}
});
});
これで、簡単なテキストエディタを導入し、.md形式のファイルを開いて表示し、変更を加えた後に保存できるようになりました。npm start
コマンドを使ってアプリを起動し、"Open"ボタンで.mdファイルを開き、テキストエディタで編集した後、"Save"ボタンで変更を保存できます。
ユーザーのPCで動くelectronでコードしたアプリを作ります。プロジェクトの初期化プロセスを教えてください