본문 바로가기

프로그래밍/Electron

Electron 시작하기-2(첫번째 Electron 앱 만들기)

Electron 
시작하기-2

< Electron 문서 >


첫 번째 Electron 앱 만들기


Electron 애플리케이션은 근본적으로 Node.js 애플리케이션이라고 할 수 있습니다. Node.js 모듈과 마찬가지로 시작점은 pakage.json 입니다. 기본적인 Electron 앱 대부분은 다음과 같은 폴더 구조를 가지고 있습니다.

your-app/
  ├── package.json
  ├── main.js
  └── index.html

새로운 Electron 애플리케이션을 위해 빈 폴더를 하나 만드세요. 커맨드 라인 클라이언트를 실행한 다음, 새로 만든 폴더 경로에서 npm init 명령어를 실행하세요.

npm init


< 커맨드 라인 클라이언트 실행 후, 명령어 입력 >

<생성된 pakage.json 정보 >
※ scripts필드를 아래와 같이 수정하였습니다.

npm은 기본적인 pakage.json파일을 생성하여 정보를 줄 것입니다. main필드에 명시된 스크립트는 앱을 시작하는 스크립트이며, 메인 프로세스에서 실행될 것입니다. 
주의 사항 : pakage.jsonmain 필드가 없는 경우, Electron은(Node.js처럼) index.js를 로드하려고 할 것입니다. 이것이 간단한 Node 애플리케이션이었다면, 현재 패키지를 실행하는 node 명령어를 start 스크립트를 통해 추가할 수 있습니다.

{ "name": "your-app", "version": "0.1.0", "main": "main.js", "scripts": { "start": "node ." } }

이 Node 애플리케이션을 Electron 애플리케이션으로 전환하는 것은 매우 간단합니다. -node 런타임을 electron 런타임으로 변경하기만 하면 됩니다.

{
    "name": "your-app",
    "version": "0.1.0",
    "main": "main.js",
    "scripts": {
      "start": "electron ."
    }
}



Electron 설치하기


이 시점에서 electron 스스로 설치해야 합니다. 권장하는 방법은 앱에 개발 의존성으로 설치하는 것입니다. 

npm install --save-dev electron

Electron 설치를 위한 다른 수단들이 있습니다. 프록시, 미러 및 사용자 정의 캐시와 함께 사용방법은 설치 설명서를 참조하세요.

< 커맨드 라인 클라이언트에서 "npm install electron --save-dev" 명령어 실행 화면 >


Electron 간단한 개발


index.js, index.html, package.json 파일을 만들어야 합니다.

Electron 앱은 Node.js 개발과 동일한 원칙과 메소드를 사용하여 JavaScript로 개발됩니다. Electron에 있는 모든 API와 기능은 Node.js 모듈과 마찬가지모듈을 통해 액세스 할 수 있습니다.

const electron = require('electron')

이 electron 모듈은 네임 스페이스의 기능을 제공합니다. 예를들어, 응용 프로그램의 수명주기를 통해 electron.app이 관리되며, 창을 electron.BrowserWindow 클래스를 사용하여 만들 수 있습니다. 간단한 index.js 파일은 응용 프로그램이 준비되고 창을 열 때까지 기다릴 수 있습니다.

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

const path = require('path') const url = require('url') function createWindow () { // Create the browser window. win = new BrowserWindow({width: 800, height: 600}) // and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) } app.on('ready', createWindow)

개발자는 index.js를 만들고 응용 프로그램에서 발생할 수 있는 모든 시스템 이벤트를 처리해야 합니다. 

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

const path = require('path') const url = require('url') // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let win function createWindow () { // Create the browser window. win = new BrowserWindow({width: 800, height: 600}) // and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null }) } // 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.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) 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 (win === null) { createWindow() } }) // 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.

마지막으로 index.html 웹페이지를 만듭니다.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </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>


앱 실행하기 


처음 index.js, index.html package.json파일을 만들고 나면 npm start 응용 프로그램의 디렉토리에서 실행 하여 응용 프로그램을 시험해 볼 수 있습니다 .

< 앱 실행 결과 >


Electron 예제 실행해보기


electron/electron-quick-start 저장소를 사용하여 자습서의 코드를 복제하고 실행하세요.
참고 : 이거서을 실행하려면 Git이 필요합니다.

# Clone the repository $ git clone https://github.com/electron/electron-quick-start # Go into the repository $ cd electron-quick-start # Install dependencies $ npm install # Run the app $ npm start

개발 과정을 시작할 수있는 상용구 및 도구 목록은 상용구 및 CLI 설명서를 참조하십시오.

'프로그래밍 > Electron' 카테고리의 다른 글

Electron 시작하기-1(Node설치 및 Electron Demos 시작)  (0) 2018.05.02
Electron 개요  (0) 2018.05.02