반응형

Vue.js를 사용해서 일렉트론 앱을 만드는 법에 대해 알아봅니다.

 

Vue CLI 설치

우선 Vue cli를 전역으로 설치합니다.

  • 기존 vue/cli가 @vue/cli로 변경되었습니다.
  • 이전버전이 설치되어 있다면 삭제 후에 설치해 주세요(npm uninstall vue/cli)
npm i -g @vue/cli

설치가 완료되면 다음 명령으로 설치 버전을 확인합니다.

vue --version

 

Vue 프로젝트 생성

이제 vue 프로젝트를 만듭니다.

  • 프로젝트명 : elec-vue
vue create elec-vue
  • Vue 버전 선택 : 최신 버전인 Vue 3를 선택합니다.

  • 아래와 같이 설치가 진행됩니다.

  • 잠시 후 설치가 완료됩니다.

  • 다음 명령어로 프로젝트를 실행합니다.
yarn serve

  • http://localhost:8080으로 접속하면 다음과 같은 화면이 나옵니다.

  • ctrl + C를 눌러 실행을 종료합니다.

 

프로젝트에 Electron Builder 추가

Electron Builder는 기존 프로젝트를 Electron으로 바꿔주고 쉽게 build를 할 수 있게 돕습니다.

Vue CLI Plugin으로 제공하는 Electron을 사용하면 쉽게 설치가 가능합니다.

https://nklayman.github.io/vue-cli-plugin-electron-builder/

 

Vue CLI Plugin Electron Builder

 

nklayman.github.io

  • 다음 명령으로 Electron Builder를 추가합니다.
vue add electron-builder
  • Electron 버전 선택 : 13.0.0

  • 설치가 완료되면 package.json에 다음과 같이 스크립트가 추가됩니다.'

 

Electron 실행

  • 이제 Electron이 추가된 프로젝트를 실행합니다.(package.json 참고)
yarn electron:serve
  • 실행 화면은 다음과 같습니다.

 

Electron Build

  • 다음 명령으로 App을 Build 할 수 있습니다.
yarn electron:build
  • 빌드가 완료되면 다음과 같이 dist_electron 폴더에 실행 파일이 생성됩니다.
    • 맥의 경우 dmg 파일로, 윈도우의 경우는 exe 파일로 생성됩니다.

  • 생성된 실행파일을 더블클릭하면 다음과 같이 Application이 실행됩니다.

이렇게 vue 프로젝트에 electron builder를 추가하면 쉽게 electron+vue 프로젝트를 만들 수 있습니다.

 

반응형
반응형

이 글의 동영상 강의입니다.

https://youtu.be/ytB0vOdZaJc

React + Electron IPC 통신하기

 

이전 12번 강좌에 이어서 진행합니다.

 

이번 강좌는 일렉트론과 React로 만들어진 프로젝트에서 IPC 통신을 하는 코드를 만들어봅니다.

실무 프로그램에서 사용되는 중요한 항목입니다.

 

기존 소스 클론하기

우선 이전 강좌에서 만든 Electron과React를 결합하여 한번에 실행하는 프로젝트의 소스를 github에서 클론합니다.

https://github.com/CodeGearGit/react-electron
 

GitHub - CodeGearGit/react-electron: React + Electron Project - Basic Setting

React + Electron Project - Basic Setting. Contribute to CodeGearGit/react-electron development by creating an account on GitHub.

github.com

  • github 사이트의 repository에서 react-electron의 code를 클릭하여 URL을 Copy합니다.
repository url copy
  • 로컬 workspace 폴더에서 git clone 실행합니다.
    프로젝트명은 "electron-react-ipc"로 합니다.
    Visual Studio Code를 실행해 프로젝트를 만들 상위폴더를 엽니다.
    터미널에 아래 명령을 실행합니다.
git clone https://github.com/CodeGearGit/react-electron.git react-electron-ipc
  • 프로젝트의 패키지들을 설치합니다.
npm install
  • 프로젝트를 실행합니다.
npm start
  • 오류없이 실행이 완료되면 아래와 같은 화면이 나옵니다.

Electron+React 실행화면

 

IPC 통신하기

 

일렉트론과 리액트간의 IPC 통신을 위한 코드를 작성합니다.

  • 일렉트론 소스와 리액트에서 동일한 코드를 사용하기 위해 상수를 정의합니다.
    src/constants.js를 추가하고 다음 코드를 추가합니다.
module.exports = { 
    SEND_MAIN_PING: 'send_main_ping', 
};
  • 일렉트론에서 요청을 받는 코드를 추가합니다.
    src/main.js를 아래와 같이 수정합니다.
    1. ipcMain 선언
    2. 상수 정의 추가
    3. ipc callback function의 코드 추가 - ipcMain.on
const { app, BrowserWindow, ipcMain } = require('electron')  
const path = require('path')  
const { 
  SEND_MAIN_PING 
} = require('./constants'); 
function createWindow () {  
  const win = new BrowserWindow({  
    width: 800,  
    height: 600,  
    webPreferences: {  
      nodeIntegration: true, 
      contextIsolation : false, 
    }  
  })  
  win.loadURL("http://localhost:3000") 
}  
ipcMain.on(SEND_MAIN_PING, (event, arg)=>{ 
  console.log('Main received a ping!!!'); 
}) 
app.whenReady().then(() => {  
  createWindow()  
})  
app.on('window-all-closed', function () {  
  if (process.platform !== 'darwin') app.quit()  
})
  • 리액트에서 ipc send 코드를 추가합니다.
    1. constants 추가
    2. ipcRenderer 추가
    3. ipc send function 추가
    4. ipc send function을 호출하는 버튼 추가
import logo from './logo.svg'; 
import './App.css'; 
import { SEND_MAIN_PING } from './constants'; 
function App() { 
  const { ipcRenderer } = window.require("electron"); 
  const sendMail = () => { 
    ipcRenderer.send(SEND_MAIN_PING, 'send'); 
  } 
  return ( 
    <div className="App"> 
      <header className="App-header"> 
        <img src={logo} className="App-logo" alt="logo" /> 
        <p> 
          Hello world!!! 
        </p> 
        <a 
          className="App-link" 
          href="https://reactjs.org" 
          target="_blank" 
          rel="noopener noreferrer" 
        > 
          Learn React 
        </a> 
        <button onClick={ sendMail }>Send Mail</button> 
      </header> 
    </div> 
  ); 
} 
export default App;
  • 프로그램을 실행합니다.
npm start
  • 화면에서 버튼을 클릭합니다.
    터미널 창에서 ipc callback function의 로그를 확인합니다.

이상으로 react+electron 프로젝트에서 IPC 통신하는 법을 알아보았습니다.

 

소스코드는 다음에서 확인하실 수 있습니다.

https://github.com/CodeGearGit/react-electron-ipc

 

GitHub - CodeGearGit/react-electron-ipc: react+electron 프로젝트에서 ipc 사용법

react+electron 프로젝트에서 ipc 사용법. Contribute to CodeGearGit/react-electron-ipc development by creating an account on GitHub.

github.com

 

반응형
반응형

이 글의 동영상 강의입니다.

https://youtu.be/0w2xmQ8q--s

 

title

최종 소스는 github를 참고하시기 바랍니다.

https://github.com/CodeGearGit/react-electron

 

GitHub - CodeGearGit/react-electron: React + Electron Project - Basic Setting

React + Electron Project - Basic Setting. Contribute to CodeGearGit/react-electron development by creating an account on GitHub.

github.com

 

이전에 진행했던 05.React 프로젝트에 일렉트론을 추가하는 법 에 이어서

 

05.React 프로젝트에 일렉트론을 추가하는 법

동영상 강좌 https://youtu.be/o4ZjkibiD8A 리액트 프로젝트 만들기(create-react-app) npx create-react-app "프로젝트명"을 사용하여 React Application을 만듭니다. npx create-react-app react-electron 리액..

codegear.tistory.com

보다 더 개발이 편리한 형태로 환경 구축을 진행해 봅니다.
이 환경을 기반으로 일렉트론 실전 프로젝트를 진행할 예정입니다.

npx create-react-app을 이용해 react-electron이라는 React 프로젝트를 만듭니다.

npx create-react-app react-electron

프로젝트 폴더로 이동후 vscode(visual studio code)를 실행합니다.

cd react-electron code .

vscode의 터미널을 열고 yarn start로 프로젝트를 실행하여 프로젝트가 잘 작동하는지 확인합니다.

yarn start

프로젝트에 일렉트론 패키지를 추가합니다.

  • electron 패키지는 개발시에만 사용하므로 --dev 옵션을 사용합니다.
yarn add --dev electron

package.json에서 electron 관련 설정을 추가합니다.

  • "main": "src/main.js" --> 일렉트론의 entry point를 main.js로 설정
  • "electron": "electron ." --> 일렉트론 실행 스크립트
{ ... "main": "src/main.js", 
  ... "scripts": { 
       ... "electron": "electron ." 
       } 
  ... 
}

src/main.js를 다음과 같이 만듭니다.

  • 이때 리액트 화면을 일렉트론에서 보여주기 위해서,
  • win.loadFile을 win.loadURL("http://localhost:3000")로 변경합니다.
const { app, BrowserWindow } = require('electron') 
const path = require('path') 
function createWindow () { 
  const win = new BrowserWindow({ 
    width: 800, 
    height: 600, 
    webPreferences: { 
      nodeIntegration: true,
      contextIsolation : false
    } 
  }) 
  win.loadURL("http://localhost:3000")
} 
app.whenReady().then(() => { 
  createWindow() 
}) 
app.on('window-all-closed', function () { 
  if (process.platform !== 'darwin') app.quit() 
})

Electron과 React를 같이 실행하기 위해 다음 패키지를 추가합니다.

  • concurrently : 일렉트론과 리액트 프로세스를 동시에 실행하기 위해 사용합니다.
  • wait-on : 프로세스 동시 수행시 한개의 프로세스가 완료되기를 기다리다 완료된 후 다음 프로세스를 수행하게 만들어 줍니다.
yarn add --dev concurrently wait-on

package.json에 스크립트를 변경합니다.

  • start 스크립트 수행시 concurrently를 이용해 react와 electron을 같이 시작하게 합니다.
  • electron 스크립트는 react가 완료되길 기다린 후 실행하게 합니다.
"scripts": {
    "start": "concurrently \"yarn react-scripts start\" \"yarn electron\" ",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "electron": "wait-on http://localhost:3000 && electron ."
},

프로젝트를 실행합니다.

yarn start

이때 브라우저가 창이 먼저 뜨고 electron이 실행됩니다. 브라우저 창은 불필요하므로 띄우지 않도록 환경 설정을 합니다.

  • 루트 폴더에 .env 파일을 만들고, 다음 내용을 추가합니다.
BROWSER=none

다시 실행하면 다음과 같이 일렉트론에서 리액트를 실행한 화면이 나옵니다.

Electron with React

소스 코드 변경 후 화면이 바로 변경되는지 확인합니다.

  • App.js에서 다음 코드를
<p> Edit <code>src/App.js</code> and save to reload. </p>
  • 아래 코드로 변경합니다.
<p> Hello! World. </p>

파일을 저장하면 다음과 같은 화면이 보입니다.

  • 소스 변경시 자동 반영되는 것을 "hot deploy"라고 합니다.

hot deploy

변경된 화면은 다음과 같습니다.

Hello! world!

이상으로 일렉트론과 리액트를 이용한 개발환경 구성을 마쳤습니다.
리액트를 좀 아시는 분이라면 이 환경에서 편하게 개발을 하실 수 있습니다.

수고하셨습니다.

반응형
반응형

일렉트론 MySQL 연동

일렉트론에서 MySQL을 연동하여 데이터를 읽어오는 것을 배워봅니다.

 

이 글의 동영상 강의입니다.

https://youtu.be/3EqAud7cBGY

Database와 Data 생성

MySQL Workbench를 실행합니다.

아래 쿼리로 스키마를 생성합니다.

 

CREATE SCHEMA test;

사용자를 생성하고 권한을 설정합니다.

CREATE USER 'test'@'localhost' identified with mysql_native_password by 'test';
GRANT ALL PRIVILEGES ON test.* TO 'test'@'localhost';
flush privileges;

Workbench에서 Connection을 추가합니다.

New Connection

설정한 Connection으로 접속합니다.

Connection

테이블을 생성합니다.

CREATE TABLE IF NOT EXISTS `test`.`user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `userid` VARCHAR(50) NULL,
  `username` VARCHAR(50) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

아래와 같이 생성된 테이블에 데이터를 입력합니다.

insert into test.user(userid, username) values ('codegear', '코드기어');
insert into test.user(userid, username) values ('ironman', '아이언맨');
insert into test.user(userid, username) values ('spiderman', '스파이더맨');

data 확인

일렉트론 Appllication 만들기

다음 스크립트로 일렉트론 Application을 만듭니다.

npx create-electron-app electron-mysql

mysql 사용을 위해 'mysql' 패키지를 설치합니다.

npm i mysql

src/index.html을 다음 코드를 입력합니다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self';">
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <h1>💖 Hello World!</h1>
    <p>Welcome to your Electron application.</p>
    <input type="button" id="btn" value="connectToMysql"/>
    <div id='users'></div>
    <script src='./function.js'></script>
  </body>
</html>

src/function.js를 만들고 다음 코드를 입력합니다.

const mysql = require('mysql');

function setInnerHTML(text) {
    const element = document.getElementById('users');
    element.innerHTML += '<div>'+text+'</div>';
  } 

document.getElementById("btn").addEventListener("click", ()=>{
    //ipc.send('getUsers');
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'test',
        password : 'test',
        database : 'test'
    });

    connection.connect();

    connection.query('SELECT * from USER', function (error, results, fields) {
        if (error) throw error;
        console.log('users: ', results);
        results.forEach(user => {
            setInnerHTML(user.username);
        });
    });

    connection.end();
})

application을 실행합니다.

npm start

"require is not defined" 오류를 확인할 수 있습니다.

require is not defined

src/index.js의 createWindow에 다음 내용을 추가합니다.

    webPreferences: {
      nodeIntegration: true,
      contextIsolation : false
    }

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : false
    }
  });

Application을 다시 실행하면 아래와 같은 결과를 확인할 수 있습니다.

Completed!!!

반응형
반응형

이 글의 동영상 강의

https://youtu.be/_KMmhsVPbk0

완성 화면

  • 아래와 같이 사이드 메뉴가 추가된 화면을 만들어보도록 하겠습니다.

완성 화면

사이드 메뉴 추가하기

이전 시간에 진행했던 타이틀바 프로젝트로 계속 진행합니다.

 

Side Sliding Menu CSS

CSS Sliding menu with scroll, no JS were used...

codepen.io

 

Side Sliding Menu CSS

VSCode로 이전 프로젝트를 불러옵니다.

  • codepen의 html에서 <nav></nav> 부분을 복사해서, index.html의 </container>뒤에 붙여넣습니다.
  • codepen의 css를 전체 복사해 src/css/menu.css를 만들고 붙여 넣습니다.
  • index.css의 body를 제외한 나머지 부분을 src/css/menu.css에 붙여 넣습니다.
  • 아래와 같이 src/css/menu.css를 수정합니다.
.title{
  height: auto;
  padding: 20px;
  display: inline-block;
}
...
@import url(../font-awesome-4.7.0/css/font-awesome.css);
...
  • 프로젝트를 실행합니다.
npm start
  • 실행화면에서 타이틀바의 높이를 확인합니다.
    • DevTools의 선택도구를 이용

  • title-bar이 높이와 동일하게 side-bar의 위치를 맞춥니다.
.main-menu {
    position: absolute;
    margin-top: 58px;
    ...
  • 완료된 화면은 다음과 같습니다.

사이드바 추가화면

반응형
반응형

이 글의 동영상 강의

https://youtu.be/si9l7uXKeq8

일렉트론에서 이벤트 처리 개념

IPC Communication

  • 일렉트론이 실행되면 main과 renderer 두개의 프로세스가 실행됩니다.
  • main은 native 기능을, renderer는 web 개발 모듈의 화면 처리를 담당합니다.
  • main과 rederer 사이의 통신은 IPC(Inter Process Communication)가 담당합니다.
  • 일렉트론 IPC는 ipcMain과 ipcRenderer 두가지가 있습니다.
  • ipcMain 은 main 프로세스에서 ipcRenderer는 renderer 프로세스에서 사용되며 상호간 communication에 사용됩니다.

일렉트론 디폴트 타이틀바 제거

  • index.js의 createWindow에서 frame: false 를 추가합니다.
const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : false
    }
  });
  
  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

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


버튼의 기능 추가하기

  • src/function.js 파일을 추가합니다.
  • function.js에 다음 코드를 추가합니다.
  • ipcRender의 send를 이용하여 main 프로세스로 이벤트를 요청합니다.
const { ipcRenderer } = require('electron');
const ipc = ipcRenderer;

var btnMin = document.getElementById("min");
var btnMax = document.getElementById("max");
var btnClose = document.getElementById("close");

btnMin.addEventListener("click", ()=>{
    ipc.send('minimizeApp');
});
btnMax.addEventListener("click", ()=>{
    ipc.send('maximizeApp');
});
btnClose.addEventListener("click", ()=>{
    ipc.send('closeApp');
});
  • index.html의 body 마지막에 function.js를 추가합니다.
<script src='./function.js'></script>


Main 프로세스에서 이벤트 처리하기

  • index.js에 ipcMain을 추가합니다.
const { app, BrowserWindow, ipcMain } = require('electron');
const ipc = ipcMain;
  • index.js의 createWindow function에 callback function을 추가합니다.
  ipc.on('minimizeApp', ()=>{
    mainWindow.minimize();
  })

  ipc.on('maximizeApp', ()=>{
    if(mainWindow.isMaximized()){
      mainWindow.restore();
    } else {
      mainWindow.maximize();
    }
  })

  ipc.on('closeApp', ()=>{
    mainWindow.close();
  })

앱을 실행합니다.

npm start

앱을 실행하면 메뉴바의 버튼들이 작동하는 것을 확인 할 수 있습니다.

반응형
반응형

이 글의 동영상 강의

https://youtu.be/eo16edDyau0

일렉트론의 디폴트 타이틀바를 없애고 새로운 타이틀바를 만드는 방법을 배워봅니다.

 

fontawesome 설치

  • 타이틀바에 들어갈 icon은 fontawesome을 설치하여 사용합니다.
  • google에서 fontawesome 검색합니다.

fontawesome

  • The iconic font and CSS toolkit 선택합니다.

Get Started

  • Get Started를 선택합니다.

Font Awesome 4

  • Font Awesome 4를 선택합니다.

Download

  • Download를 선택합니다.
  • download 받은 파일을 src/font-awesome에 압축 해제합니다.

일렉트론 애플리케이션 화면 상단에 메뉴바를 만들기

  • index.html에 fontawesome css를 추가합니다.
<link rel="stylesheet" href="./font-awesome/css/font-awesome.min.css">
  • 앞에 google에서 조회한 fontawesome의 Free Icons 사이트로 이동합니다.

Free Icons

  • icon 검색 창에서 minimize를 검색합니다.

minimize

  • window-minimize를 선택합니다.

window-minimize icon

  • 다음과 같이 index.html에 아이콘을 추가합니다.
<button id="min">
  <i class="fa fa-window-minimize"></i> 
</button>
  • maximize, close 아이콘도 동일한 방법으로 추가합니다.
<button id="min">
  <i class="fa fa-window-minimize"></i> 
</button>
<button id="max">
  <i class="fa fa-window-maximize"></i> 
</button>
<button id="close">
  <i class="fa fa-window-close"></i> 
</button>
  • index.html 전체 코드는 다음과 같습니다.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css">
    <link rel="stylesheet" href="./font-awesome/css/font-awesome.min.css">
  </head>
  <body>
    <div class="container">
      <div class="title-bar">
        <div class="title prevent-select draggable">Custom Title Bar</div>
        <div class="control prevent-select">
          <button id="min">
            <i class="fa fa-window-minimize"></i>
          </button>
          <button id="max">
            <i class="fa fa-window-maximize"></i>
          </button>
          <button id="close">
            <i class="fa fa-window-close"></i>
          </button>
        </div>
      </div>
    </div>
  </body> 
</html>
  • 일렉트론을 실행합니다.
npm start

실행화면

  • index.css를 다음과 같이 수정합니다.
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  margin: 0px;
}

body *{
  box-sizing: border-box;
}

.container{
  height: 100%;
  padding: 0;
  display: grid;
  grid-template-rows: auto 1fr;
}

.title{
  height: auto;
  padding: 10px;
  display: inline-block;
}

.control{
  float: right;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  margin-top: 5px;
  margin-right: 5px;
  width: 100px;
}

.control button{
  padding: 5px;
  background: #000000;
  color: #ffffff;
  outline: 0;
  border: 0;
}

.control button:hover{
  background: #444444
}

.title-bar{
  background: #000000;
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
  color: #ffffff;
  font-size: 15px;
}

.prevent-select{
  user-select: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
}

.draggable{
  -webkit-app-region: drag;
}
  • 일렉트론을 실행합니다.
npm start

디자인 완성화면

Custom Title Bar의 디자인이 완성되었습니다.

 

반응형
반응형

동영상 강의

https://youtu.be/vgic4kn1Oko

Electron 화면은 web 제작 기술과 동일합니다.

따라서 html, css, js만으로 개발이 가능합니다.

 

이번 시간은 codepen 사이트에서 맘에 드는 디자인을 가져와서 화면 디자인을 바꿔봅니다.

 

우선 일렉트론 App을 만듭니다.

npx create-electron-app electron-app

VSCode로 프로젝트를 불러옵니다.

code .

codepen.io 사이트로 이동합니다.

 

CodePen

An online code editor, learning environment, and community for front-end web development using HTML, CSS and JavaScript code snippets, projects, and web applications.

codepen.io

검색창에 "intro" 로 검색합니다.

 

ScrollMagic Wiki Tutorial : Anchor Navigation

Demo for the ScrollMagic Anchor Navigation Effect. Read the WIKI tutorial: https://github.com/janpaepke/ScrollMagic/wiki/Tutorial-:-Anchor-Navigation...

codepen.io

  • html 내용을 복사해서 index.html에 붙여 넣습니다.
  • css 내용을 복사해서 index.css에 붙여 넣습니다.
  • src/function.js 파일을 만듭니다.
  • js 내용을 복사해서 function.js에 붙여 넣습니다.
  • index.html </body>위에 <srcript src='function.js'></script>를 추가합니다.
  • yarn start 를 실행합니다.

실행화면

간단하게 일렉트론 화면을 만들어 봤습니다.

이렇게 codepen을 이용하면 디자이너 없이 약간의 수정만으로 일렉트론 개발이 가능합니다.

반응형
반응형

동영상 강좌

https://youtu.be/ojDfxv_EU1k

일렉트론의 메뉴는 다음 API 문서를 참조하시면 됩니다.

https://www.electronjs.org/docs/latest/api/menu

 

Menu | Electron

Menu Class: Menu# Create native application menus and context menus. Process: Main new Menu()# Creates a new menu. Static Methods# The Menu class has the following static methods: Menu.setApplicationMenu(menu)# Sets menu as the application menu on macOS. O

www.electronjs.org

소스는 지난시간에 만든 react-electron을 계속 사용합니다.

  • src/main.js

가장 먼저 menu를 사용하기 위해서 electron의 menu를 선언 합니다.

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

다음과 같이 template을 이용하여 menu를 setting 합니다.

  • createWindow function 다음에 아래 코드를 작성합니다.
const template = []; 
const menu = Menu.buildFromTemplate(template); 
Menu.setApplicationMenu(menu);
  • 현재는 template에 값이 없기 때문에 메뉴가 나타나지 않는 것을 볼 수 있습니다.

menu가 없이 실행됨.

  • template에 다음과 같이 메뉴를 추가합니다.
const template = [
  { 
    label: "File",
  }
]

File 메뉴 추가

  • submenu는 다음과 같이 추가합니다.
  { 
    label: "File", 
    submenu: [ 
      { 
        label: "Open" 
      }
    ] 
  }

submenu 추가

Role 메뉴

 

MenuItem | Electron

Add items to native application menus and context menus.

www.electronjs.org

  • 개발자 화면을 toggle 하는 'toggleDevTools' role을 다음과 같이 추가합니다.
{ 
    role: 'toggleDevTools', 
}

role 추가

메뉴 클릭시 이벤트 처리하기

  • 다음과 같이 Open 메뉴를 클릭했을때 console 로그를 출력하는 이벤트를 추가합니다.
{ 
    label: "Open" , 
    click: function(){ 
      console.log('Clicked Menu Open!!!');
    }
},

Type 메뉴

  • 일렉트론에서는 여러가지 type의 메뉴를 제공합니다.
  • 그 중 가장 많이 사용하는 separator를 추가해 봅니다.
{ type: 'separator' },

separator 추가

  • 'checkbox' type을 추가합니다.
{ label: 'Menu Item 2', type: 'checkbox', checked: true },

checkbox type 추가

외부 사이트 열기

  • 메뉴를 클릭했을 때 기본브라우저로 외부 URL을 호출하는 예제입니다.
  • 우선 electron의 shell을 선언 합니다.
const { app, BrowserWindow, Menu, shell } = require('electron')
  • shell.openExternal을 사용해 사이트를 호출합니다.
click: function(){
  shell.openExternal("https://www.electronjs.org/docs/api") 
}

외부 url 호출

이상으로 일렉트론의 메뉴 사용법을 알아보았습니다.

보다 자세한 사항들은 API 문서를 참조하시기 바랍니다.

반응형
반응형

동영상 강좌

https://youtu.be/o4ZjkibiD8A

리액트 프로젝트 만들기(create-react-app)

  • npx create-react-app "프로젝트명"을 사용하여 React Application을 만듭니다.
npx create-react-app react-electron

리액트 프로젝트 실행

yarn start
  • http://localhost:3000 으로 실행됩니다.

일렉트론 패키지 추가

yarn add --dev electron

일렉트론 실행 스크립트 추가

  • package.json에 다음과 같이 스크립트를 추가합니다.
"scripts": {
	...
	"electron": "electron ."
},

일렉트론 Entry point 스크립트 추가

"main": "src/main.js",

main.js 만들기

  • src/main.js 파일을 생성합니다.
  • electron-quick-start의 main.js를 복사하여 추가합니다.
const { app, BrowserWindow } = require('electron') 
// include the Node.js 'path' module at the top of your file 
const path = require('path') 
// modify your existing createWindow() function 
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('window-all-closed', function () { 
  if (process.platform !== 'darwin') app.quit() 
})

윈도우에 리액트 URL을 불러오기

  • win.loadFile('index.html') 을 다음과 같이 변경합니다.
win.loadURL('http://localhost:3000')

실행화면

실행화면

반응형

+ Recent posts