본문으로 바로가기

Electron 기본 생성 코드 리뷰

category Study/Electron 2021. 4. 8. 13:32
반응형

main.js

const { app, BrowserWindow } = require("electron");
const path = require("path");

Electron 모듈에서 app, BrowserWindow를 로드한다.

Path를 사용하기 위해 path를 불러온다.

function createWindow() {
    // index.html/preload.js 로드
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, "preload.js"),
        },
    });

    win.loadFile("index.html");
}

CreateWindow() 함수를 생성한다.

창의 속성을 지정한 후 preload.js를 로드하도록 설정한다.

app.whenReady().then(() => {
    // 윈도우 생성
    createWindow();

    app.on("activate", () => {
        // Listener 생성
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

윈도우를 생성한 후 Listener를 생성한다.

app.on("window-all-closed", () => {
    // 창이 모두 닫히면 App 종료(맥 제외)
    if (process.platform !== "darwin") {
        app.quit();
    }
});

모든 창이 닫히면 Applicaton을 자동으로 종료한다. *맥은 운영체제 상으로 지원하지 않는다.

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]);
    }
});

DOMContentLoaded 이벤트가 발생했을 때 크롬/Node/Electron 버전을 불러와 replace한다.

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 style="background: white">
        <h1>Hello World!</h1>
        <p>
            We are using Node.js <span id="node-version"></span>, Chromium
            <span id="chrome-version"></span>, and Electron
            <span id="electron-version"></span>.
        </p>
    </body>
</html>

Source :

 

Quick Start Guide | Electron

Please install Node.js using pre-built installers for your platform. You may encounter incompatibility issues with different development tools otherwise.

www.electronjs.org

반응형