LoginSignup
0
0

More than 1 year has passed since last update.

Electronの始め方〜HelloWorldまで〜

Last updated at Posted at 2021-11-29

普段はElectronとは無縁の生活の者です。
2018年くらいの記事を読んで失敗したので書き留めます。

今回はElectronでhello worldできれば完成です!

ディレクトリ作成

mkdir helloworld

ファイルの追加

次にhelloworldディレクトリに3つファイルを追加します。

helloworld/
 ├ main.js
 ├ preload.js
 └ index.html

main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')

function 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
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})
index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello World!</h1>
</body>

npmのインストール

cd helloworld
npm init

package.jsonを編集します。

package.json
{
  "name": "helloworld",
  "version": "1.0.0",
  "description": "",
  "main": "main.js", 
  "dependencies": {
    "electron": "^16.0.2"
  },
  "devDependencies": {},
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

ここで注意する点は、
"main"の部分が"main.js"になっているか。
それと、
"script"の部分に"start"の部分を足すこと。

次に、やっとelectronのインストールに入ります。

npm install --save-dev electron

helloworldディレクトリでインストールします。当たり前だけど、間違えがち。変なディレクトリでインストールしがち。

これでOK
起動します。もちろんhelloworldディレクトリで。

npm start

スクリーンショット 2021-11-29 22.38.48.png

めでたくhelloworld!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0