💻 개발/Electron

[Electron] 일렉트론 설치 후 Hello World 출력하기

개발새발. 2024. 3. 29. 10:43

🚀 Node.js & Electron 설치방법

 

일렉트론은 처음해보는데

데스크탑용 앱을 만들 수 있다길래 도전해본다

우선 설치하고 Hello World 까치 출력해보자 

 

 

1. node.js 설치

 

1-1. 사이트에서 설치파일 다운로드 (Recommended 버전)

👉  https://nodejs.org/en

 

Node.js — Run JavaScript Everywhere

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

1-2. cmd창에서 설치여부 확인

버전은 다를 수 있지만 아래처럼 버전정보가 나오면 설치완료

$ node -v (Node.js 버전확인)
$ npm -v (npm 버전확인)

 

 


2. Electron 설치

 

2-1. 프로젝트 폴더를 만든 후 패키지를 초기화한다.

(예제는 C\Users\development에 electron-app 폴더를 생성)

$ mkdir electron-app
$ cd electron-app
$ npm init (초기화 명령어)

 

2-2. Electron 설치 후 vscode를 실행한다.

$ npm install --save-dev electron
$ code .

 


3. 초기설정

 

3-1. package.json 파일 수정

scripts 부분에 일렉트론 실행 명령어를 등록한다.

 

3-2. 초기 실행 파일 생성 (index.js)

2-1에서 패키지를 초기화하면서 entry point를 기본값(index.js)으로 설정했기 때문에

일렉트론이 실행되면 index.js 파일을 찾는다.

초기 실행 파일을 바꾸고 싶을 경우 package.json 파일의 main 부분을 수정하면 된다.

 

 

[index.js]

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

/** 메인 창 생성 */
function createWindow () { 
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: { preload: path.join(__dirname, 'preload.js') } //path.join()으로 전처리 url 또는 file을 설정할 수 있음
  })

  //브라우저창이 읽어 올 파일 위치
  win.loadFile('./index.html')
}

/** Application이 준비된 후 실행할 스크립트를 지정*/
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>
        <title>Hello, World!</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
        <p>
            It's using Node.js <span id="node-version"></span>, Chromium <span id="chrome-version"></span> and Electron <span id="electron-version"></span>.
        </p>
    </body>
</html>

 

 


4. electron 실행하기

$ npm start

'💻 개발 > Electron' 카테고리의 다른 글

[Electron] 일렉트론 상단 메뉴 바 제거 (Window용)  (0) 2024.04.17