electron アプリ で hello World !

● electron のインストール

npm install electron --save-dev

● electron アプリの作成

npx create-electron-app my-hello-app

● my-hello-app アプリの起動

cd my-hello-app
npm start

アプリが起動します

● メインプロセスとレンダラープロセス(View)とのデータのやり取り

touch src/renderer.js

renderer.js

const { ipcRenderer } = require('electron')
// DOM Ready
document.addEventListener("DOMContentLoaded", function () {
    /**
     * my-btn を押すとメインプロセスへデータを渡す
     */
    const btn = document.getElementById('my-btn')
    btn.addEventListener('click', () => {
        ipcRenderer.send('MessageMain', { message: 'レンダラーからメインプロセスへメッセージです。' });
        console.log( '● レンダラーからメッセージを送信しました' );
    });
});

index.htmlrenderer.js を読み込みます。

index.html

    <script src="renderer.js"></script>

index.js でメッセージを受けれるようにしておきます。

index.js

/**
 * レンダラープロセスからデータの受信 (MessageMain)
 *
 */
ipcMain.on('MessageMain', (event, arg) => {
  console.log( '● arg' );
  console.log( arg );
})
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  });

  ↓

  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

● my-hello-app アプリのビルド

npm run make

out フォルダにアプリができます。 (ファイルサイズが大きいのは諦めましょう)

windows 32bit用にビルド

npx electron-forge make --arch=ia32

● electronアプリのビルドサイズを小さくする

こちらを clone してビルドしてみましょう。 https://github.com/electron-react-boilerplate/electron-react-boilerplate

● Electron製アプリの起動速度を1,000ミリ秒速くする方法

https://blog.craftz.dog/how-to-make-your-electron-app-launch-1000ms-faster-bcc2997fa1f7

● electronアプリの 配布用パッケージ.dmg インストーラを作成する

electron-builderのインストール

npm install electron-builder --save-dev

● パッケージ作成を実行する

・mac 64bit 用にアプリの 配布用パッケージ.dmg インストーラを作成する

node_modules/.bin/electron-builder --mac --x64

・windows 64bit 用にアプリの 配布用パッケージを作成する

npx electron-builder --win --x64

・windows 32bit 用にアプリの 配布用パッケージを作成する

npx electron-builder --win --ia32

● .env ファイルに設定情報を記述しelectronアプリから読み込む

npm install --save dotenv

「プロジェクトのトップディレクトリ」に .env ファイルを作成します

.env

HOGE=テスト文字列

index.js

//.envに記述したデータを読み込み
require('dotenv').config();

// 環境変数の表示
  console.log('● process.env');
  console.log( process.env );

ビルドしたときもビルドしたトップディレクトリに .env を設置する必要があります。

● デフォルトのブラウザでURLを開く

const { shell } = require('electron')
shell.openExternal('https://www.google.com/')

● electronアプリをシングルインスタンスを強制する

app.on('ready', createWindow);

   ↓

const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
   .... 何かしらの行いたい処理
  setTimeout( function(app) {
    app.exit();
  }, 1500, app );
} else {
  app.whenReady().then(() => {
   .... 何かしらの行いたい処理
  });
}
No.1973
11/10 16:17

edit