본문 바로가기
시작/TIL(Today I Learned)

230811 - Electron.js 기초

by 백씨네 2023. 8. 11.
728x90

오늘 내가 배운 것

1. Eletron.js

2. 사용하기

 

 

 

 

Electron.js

일렉트론은 일반적인 웹 기술을 이용하여 데스크톱 애플리케이션을 만들기 위한 프레임워크이다.

JS, HTML/CSS를 이용하여 크로스 플랫폼 데스크톱 애플리케이션을 개발할 수 있다.

Electron은 Chrominum 웹 브라우저와 Node.js 런타임을 결합하여 사용하는 것이다.

크로스 플랫폼

크로스 플랫폼은 하나의 코드를 이용하여 여러 OS 환경, 디바이스에서 실행될 수 있게 하는 것이다.

이전에 React-Native를 이용해서 하나의 코드로 IOS, Android 환경에서 사용하는 애플리케이션을 빌드를 했던 것처럼 Electron도 하나의 코드를 이용해서 MacOS, Window, Linux OS에서 사용할 수 있는 애플리케이션을 만드는 것이다.

웹 기반

Electron은 웹을 기반으로 되어있기 때문에 웹페이지를 만들어 보았던 개발자가 쉽게 할 수 있다.

네이티브 기능

Node.js 런타임을 내장하고 있기 때문에 시스템 리소스에 접근이 가능하여 기본적인 OS 네이티브 기능을 활용할 수 있다.

대표적인 애플리케이션

  1. Visual Studio Code
  2. Slack
  3. Discode

등이 있다.

 

 

사용하기

사용하기 전에 Node가 설치되어 있어야 한다.

Node가 설치되어 있다면 아래를 진행하면 된다.

1. 기본 설치

# electron-app 디렉토리 만들기
npx create-react-app electron-app

CRA를 진행한다. electron-app이라는 디렉토리를 생성하였다.

이후 electron-app으로 진입한다.

cd electron-app

electron을 설치한다.

npm install -save-dev electron

2. package.json 설정

scripts와 main을 지정해주어야 한다.

"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject",
        "electron": "electron ." 
    },

“electron . “ 명령어를 이용해서 개발 모드에서 앱을 열 수 있다.

npm run electron‘으로 electron . 명령어를 사용하기 위해서 scripts에 지정을 해둔다.

그리고 main을 지정해야 한다.

“main”은 electron 애플리케이션의 entry point이다.

작성한 코드가 일렉트론 앱에서 실행될 때 entery point인 main.js를 이용해서 열리고 main.js에 앱에 열릴 내용을 지정해 준다고 생각하면 된다. 기본적인 앱의 설정 내용들은 여기서 지정한다.

"main": "src/main.js"

최종적으로 작성되는 package.json은 아래와 같다.

{
    "name": "react-electron",
    "version": "0.1.0",
    "private": true,
    "main": "src/main.js", // 추가
    "dependencies": {
        "@testing-library/jest-dom": "^5.17.0",
        "@testing-library/react": "^13.4.0",
        "@testing-library/user-event": "^13.5.0",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-scripts": "5.0.1",
        "web-vitals": "^2.1.4"
    },
    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject",
        "electron": "electron ." // 추가
    },
    "eslintConfig": {
        "extends": [
            "react-app",
            "react-app/jest"
        ]
    },
    "browserslist": {
        "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
        ],
        "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
        ]
    }
}

3. src/main.js

src 디렉토리 안에 main.js를 추가하여 앱의 기본 설정 및 앱을 열었을 때 바라보게 되는 파일이나 주소를 지정해 줄 수 있다.

아래는 electron의 공식문서에서 가져온 내용이다.

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

mainWindow.loadFile(”index.html”)에 의해서 index.html 파일을 읽는다는 것을 확인할 수 있다.

이를 이용해서 배포된 주소로 앱을 만들 수 있다.

// index.html 파일 열기
mainWindow.loadFile("index.html") 

//https://example.com 웹사이트를 앱으로 만들 수 있다.
mainWindow.loadURL("https://example.com") 

4. 실행하기

main.js와 loadURL을 지정한 후에 지정해 두었던 scripts를 이용해서 app을 볼 수 있다. ( 빌드되어 파일로 나오는 것이 아니라 확인하는 것이다. 실제 설치 파일로 추출하기 위해선 추가적인 작업이 필요하다.)

npm run electron

 

 

일반적인 web으로는 주소창 등 브라우저의 기본적인 것이 보이지만 electron으로는 브라우저의 기능을 제외하고 내용만 확인이 가능하다.

 

 

 

 


 

반응형

댓글