페이지

2019년 12월 16일 월요일

Electron 기반 데스크톱 앱 개발

Electron 기반 데스크톱 앱 개발

Electron은 HTML, CSS, 그리고 JavaScript를 사용하여 크로스 플랫폼 데스크톱 앱을 개발할 수 있도록 합니다. 지원하는 플랫폼은 다음과 같습니다.

  • Windows
  • macOS
  • Linux

Windows Forms를 사용하여 GUI 데스크톱 앱을 개발하는 것과 비교하여 많은 장점을 가지고 있습니다. 그 중에서 몇 가지만 나열하자면 아래와 같습니다.

  • 크로스 플랫폼 - 이제 맥북 사용자에게 "당신은 이 앱을 사용할 수 없습니다"라고 말하지 않아도 됩니다.
  • 데이터 시각화 - 다양한 차트 라이브러리를 사용하여 뛰어난 시각화 기능을 빠르고 쉽게 구현할 수 있습니다.
  • 현대적 느낌의 테마 - 큰 글자, 대담한 여백, 고급스러워 보이는 색상 등 웹에서 경험할 수 있는 테마를 데스크톱 앱에서도 제공할 수 있습니다.
  • 글자 확대/축소 - 노안이 찾아 오는 40대 중후반 이후 연령대의 사용자에게는 매우 고마운 기능입니다.
  • 반응형 UI 디자인 - 작은 화면의 컴퓨터를 사용하는 사용자에게 유용할 것입니다.
  • 편리한 디버깅 - 구글 크롬 브라우져의 개발자 도구와 같은 방식으로 디버깅을 할 수 있습니다.

이 문서에서는 아래의 내용을 다루며 설명은 Windows 시스템을 기준으로 진행합니다.

  1. 개발 환경 준비
  2. 간단한 앱 작성 및 실행
  3. 패키징
  4. 디버깅

Node.js 설치

  1. Node.js 다운로드 페이지에서 LTS 버전의 Windows Installer를 선택합니다. 이 문서를 작성하는 시점에서 최신 버전은 12.13.0(npm 6.12.0 포함)입니다.
  2. 다운로드한 파일을 더블클릭하여 설치를 시작합니다. 설치되는 항목은 아래와 같습니다.
    • Node.js runtime
    • npm package manager
    • Online documentation shortcuts
    • Add to PATH
  3. Tools for Native Modules 화면에서 아래 옵션을 선택합니다.
    • Automatically install the necessary tools. Note that this will also install Chocolatey. The script will pop-up in a new window after the installation completes.
  4. Node.js 설치가 끝나면 아래 스크립트 창이 뜹니다. 엔터키를 눌러서 Tools for Node.js Native Modules 설치를 진행합니다.
    ====================================================
    Tools for Node.js Native Modules Installation Script
    ====================================================
    
    This script will install Python and the Visual Studio Build Tools, necessary
    to compile Node.js native modules. Note that Chocolatey and required Windows
    updates will also be installed.
    
    This will require about 3 Gb of free disk space, plus any space necessary to
    install Windows updates. This will take a while to run.
    
    Please close all open programs for the duration of the installation. If the
    installation fails, please ensure Windows is fully updated, reboot your
    computer and try to run this again. This script can be found in the
    Start menu under Node.js.
    
    You can close this window to stop now. Detailed instructions to install these
    tools manually are available at https://github.com/nodejs/node-gyp#on-windows
    
    계속하려면 아무 키나 누르십시오 . . .
    
  5. Tools for Node.js Native Modules 설치가 끝나면 아래와 같은 결과가 출력됩니다. 엔터키를 눌러서 설치 스크립트 화면을 닫습니다. 일부 패키지는 시스템 재시작을 필요로 합니다.
    Upgraded:
     - visualstudio2017buildtools v15.9.17.0
     - kb2919355 v1.0.20160915
     - kb3033929 v1.0.5
     - python2 v2.7.17
     - kb2999226 v1.0.20181019
     - chocolatey-core.extension v1.3.4
     - dotnetfx v4.8.0.20190930
     - chocolatey-visualstudio.extension v1.8.1
     - visualstudio2017-workload-vctools v1.3.2
     - kb2919442 v1.0.20160915
     - visualstudio-installer v2.0.1
     - vcredist140 v14.23.27820
     - chocolatey-dotnetfx.extension v1.0.1
     - kb3035131 v1.0.3
     - chocolatey-windowsupdate.extension v1.0.4
    
    Packages requiring reboot:
     - vcredist140 (exit code 3010)
    
    The recent package changes indicate a reboot is necessary.
     Please reboot at your earliest convenience.
    Type ENTER to exit:
    

첫번째 Electron 앱 만들기

  1. 앱을 만들고자 하는 폴더에서 명령 프롬프트 창을 열고 아래 명령을 실행합니다.

    >npm init
    

    선택 옵션에 대하여 모두 엔터키를 치면 기본값을 사용하여 package.json 파일을 생성할 것입니다.

  2. package.json 파일을 열어서 scripts 항목에 아래와 같이 start 항목을 추가하고 저장합니다. 이것은 앱을 실행할 때 Electron 런타임을 사용하도록 지정하는 것입니다.

    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "electron ."
    }
    
  3. 앱 폴더에서 아래 명령을 실행하여 Electron을 설치합니다.

    >npm install electron -g
    

    앱별로 Electron을 설치하여 사용하고자 한다면 아래의 명령으로 설치합니다.

    >npm install electron --save-dev
    
  4. 앱 폴더에서 아래와 같은 내용으로 index.js 파일을 작성합니다.

    const { app, BrowserWindow } = require('electron')
    
    function createWindow () {
      // Create the browser window.
      let win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
    
      // and load the index.html of the app.
      win.loadFile('index.html')
    }
    
    app.on('ready', createWindow)
    
  5. 앱 폴더에서 아래와 같은 내용으로 index.html 파일을 작성합니다.

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Hello World!</title>
        <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
      </head>
      <body>
        <h1>Hello World!</h1>
        We are using node <script>document.write(process.versions.node)</script>,
        Chrome <script>document.write(process.versions.chrome)</script>,
        and Electron <script>document.write(process.versions.electron)</script>.
      </body>
    </html>
    
  6. 앱 폴더에서 아래 명령으로 Electron 앱을 실행합니다.

    >npm start
    

    앱이 정상적으로 실행되면 아래와 같은 화면이 표시될 것입니다.

패키징

  1. 아래 명령을 실행하여 Electron Packager를 설치합니다.
    >npm install electron-packager -g
    
  2. 앱 폴더에서 아래 명령을 실행하여 현재 시스템을 대상으로 하는 배포 번들을 만듭니다.
    >electron-packager ./ hello-world
    
    첫번째 실행인자 ./는 소스 폴더 위치이고 두번째 실행인자 hello-world는 앱 이름입니다. 배포 번들은 <appname>-<platform>-<architecture> 규칙으로 생성된 폴더 아래에 저장됩니다. 위 명령을 Windows (64 비트) 시스템에서 실행하고 있기 때문에 배포 번들은 hello-world-win32-x64 폴더에 생성됩니다.
  3. 다른 플랫폼을 대상으로 배포 번들을 만들고자 한다면 platformarch 옵션을 사용하여 대상을 지정할 수 있습니다.
    >electron-packager ./ hello-world --platform=linux --arch=x64
    >electron-packager ./ hello-world --platform=darwin --arch=x64
    
    관리자 권한으로 연 명령 프롬프트 창이 아닐 경우 darwin을 대상으로 지정한 명령을 수행하면 아래와 같은 에러가 출력됩니다.
    EPERM: operation not permitted, symlink 'C:\Users\usera\AppData\Local\Temp\electron-packager\symlink-test\test' -> 'C:\Users\usera\AppData\Local\Temp\electron-packager\symlink-test\testlink'
    

실행 및 디버깅

  1. hello-world-win32-x64 폴더 아래에 있는 hello-world.exe 파일을 실행합니다.
  2. 앱 화면에서 View > Toggle Developer Tools 메뉴 항목을 클릭합니다. 그러면 HTML/CSS/JavaScript 를 디버깅할 수 있는 창이 화면 오른쪽에 표시됩니다.

참고 자료

  1. Electron Documentation - Developer Environment
  2. Electron Documentation - Writing Your First Electron App
  3. Electron Packager

Written with StackEdit.

댓글 2개:

  1. elctron을 처음 접하면서 앱을 만들어 보려고 합니다. AppJS로 기존 다른 분이 작성해놓은것을 electron환경에서 해보고자 하면서,작성자님 글대로 잘 작성해보고 있습니다.
    문제가 한개 있는데요.
    index.js , index.html 을 활용하는데 index.html에서 실제 app 구동을 위한 별도의script.js를 만들어 사용하는데,
    index.js에서 fs=require('fs')와 같이 필요한 모듈을 사전에 로드하고 해당 fs 객체를 script.js에서 사용하고 싶습니다. 현재 방법을 못찾아서 App 실행하면

    script.js에서 "Uncaught ReferenceError: fs is not defined"

    이런식의 에러가 발생합니다. 해결방법이 있을가요?

    http
    fs
    url
    3개의 모듈을 전달해야할듯 합니다.

    답글삭제
  2. 감사합니다.
    이게 도대체 무슨말이지 하고 찾아봤는데
    이렇게 딱! 친절히 자세히 설명해 주셔서 덕분에 성공했어요~

    답글삭제

국어 맞춤법 참고 자료

  제목 설명(인용) 출처 IT 글쓰기와 번역 노트 IT 기술 문서 및 서적을 집필/번역/교정하면서 얻은 경험/정보/지식을 공유합니다. 전뇌해커 [우리말 바루기] ‘대로’의 띄어쓰기 명사 뒤에서는 붙여 쓰고, 그 외에는 띄어 쓴다고 생각하면 쉽다. 다...