티스토리 뷰

안녕하세요. 09LABS 입니다.
요즘 프로그래밍을 하면서 Frontend + Backend Application을 만들어보고 싶다는 생각에
새 프로젝트를 시작하면서 Electron에 대해 접하게 되었습니다.


동료의 얘기로는 Electron이 가장 많이 사용되는 프레임워크라고 했고 Javascript 이기 때문에 C, C++로 개발을 했었던 제가 처음 접하기에 큰 어려움이 없을 것이라고 했습니다.
Electron은 JavaScript와 HTML, CSS를 사용하여 Desktop Application을 만들 수 있는 Framework 입니다.
Windows, MacOS, Linux 모두 사용할 수 있는 크로스 플랫폼이기 때문에 OS를 가리지 않는다는 장점이 있습니다.

어떤 언어를 시작하더라도 Hello World를 띄우는 것이 가장 처음 할 일이겠죠?
Electron 공식 홈페이지 글을 보고 시작 해보겠습니다.

먼저 Node.js가 설치되어 있어야 합니다. 설치되어있지 않다면 설치를 먼저 하고 오시기 바랍니다.

Package Initialize

npm init

적당히 아무 폴더나 생성한 뒤 위 명령어를 입력합니다.
윈도우에서는 PowerShell을 실행한 뒤 npm.cmd init을 입력해주면 됩니다.

$ npm.cmd init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (bambuelectron)
version: (1.0.0)
description:
entry point: (index.js) main.js
test command:
git repository:
keywords:
author:
license: (ISC)

About to write to C:\Users\Documents\testapplication\package.json:     

{
  "name": "testapplication",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
  },
  "author": "",
  "license": "ISC",
  "description": ""
}

entry point만 main.js로 바꿔주고 엔터를 입력해서 넘어가면 위와 같이 package.json 파일을 생성해 줍니다.
그 다음 아래 명령어를 입력해서 Electron Dependency를 추가합니다.

npm i --save-dev eletron

여기까지 완료하셨다면 start 스크립트를 추가합니다.

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

이제 화면을 만들어줄 차례입니다. 폴더에 index.html 파일을 생성해서 아래 내용을 입력해줍니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

이제 HTML로 작성한 웹 페이지를 Application 창에 띄울 차례입니다.
main.js 파일을 만들고 아래와 같이 입력합니다.

const { app, BrowserWindow } = require('electron');
const path = require('path');
 
const createWindow = () => {
    const win = new BrowserWindow({
        width: 640,
        height: 480,
        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();
});

우선 Hello World를 띄우는 것이기 때문에 자세한 설명은 생략하겠습니다.
간단히 요약하면 윈도우의 생명 주기, 어떤 화면을 띄울 것인지, 창 크기는 어떻게 되는지 정의가 되어있습니다.
마지막으로 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]);
    }
});

preload.js는 Electron과 종속성에 대한 내용을 웹 페이지에 띄우기 위한 내용이 정의되어 있습니다.
작성이 완료되었다면 아래와 같이 명령어를 입력합니다.

$ npm start

창에 HTML로 작성된 웹 페이지가 실행된 것을 알 수 있습니다.
의도한대로 Cromium, Node.js, Eletron 버전이 표시됩니다.

이렇게 해서 첫 Electron Application을 만들어 봤습니다.
다음장에서는 UI를 꾸미고 Electron으로 앱을 실행하는 방법에 대해 알아보겠습니다.

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함