html,css,js로 데스크탑 앱을 만드는 방법

자바스크립트로 데스크탑 앱을 만들 수 있다는 사실을 알고 계셨습니까? electron.js라는 이름의 js 프레임워크가 있습니다. 이에 대한 자습서를 만들려고 생각 중이었습니다. 시작해 보겠습니다.
시작하기 전에, 나는 당신이 가지고 있기를 바랍니다
- HTML, CSS, JS에 대한 기본 지식
-node.js가 시스템에 설치됨
- node.js에 대한 기본 지식

목차:

Explaination
Build
Paybacks of using Electron

1장

Structure of an Electron.js App



-Chromium: 웹 페이지 생성 및 표시를 담당하는 Electron.js 구조의 구성 요소입니다. 웹 콘텐츠는 Electron.js의 Renderer 프로세스(나중에 자세히 설명)에 표시되며 Chromium 환경으로 인해 일반적인 Google Chrome 브라우저에서 작동하는 것처럼 모든 브라우저 API 및 개발 도구에 액세스할 수 있습니다.
-Node.js: 이것은 시스템 기능에 대한 액세스를 제공하는 Electron.js 구조의 구성 요소입니다. Electron.js는 Main 프로세스에서 Node.js를 실행합니다(자세한 내용은 나중에 설명). 이를 통해 파일 시스템, 운영 체제 등과 상호 작용하는 것과 같이 Node.js가 제공하는 모든 것에 액세스할 수 있습니다.
-사용자 지정 API: 개발자가 일반적인 데스크톱 경험을 만들고 기본 기능으로 쉽게 작업할 수 있도록 Electron.js에는 컨텍스트 메뉴 생성 및 표시, 바탕 화면 알림 표시, 키보드 작업과 같은 작업을 수행하는 데 도움이 되는 사용하기 쉬운 라이브러리 API가 있습니다. 단축키 등

실행 중인 Electron.js 앱은 Main 프로세스와 하나 이상의 Renderer 프로세스라는 두 가지 유형의 프로세스를 유지 관리합니다. 진입점은 Main 프로세스입니다.
메인 프로세스는 웹 페이지 생성을 담당합니다. Electron.js BrowserWindow 객체의 새 인스턴스를 생성하여 이를 수행합니다. 이것은 자체 렌더러 프로세스에서 실행되는 새 웹 페이지를 만듭니다. 메인 프로세스는 각각 자체 렌더러 프로세스에서 실행되는 둘 이상의 웹 페이지를 생성할 수 있습니다.

일반적으로 Electron.js 애플리케이션은 앱의 시작 화면인 기본 웹 페이지로 부팅됩니다. 그런 다음 응용 프로그램에 필요한 경우 더 많은 화면을 만들 수 있습니다.

각 Renderer 프로세스는 자체 웹 페이지를 관리하며 다른 Renderer 프로세스 및 Main 프로세스 자체와 완전히 격리되어 있습니다. 따라서 한 렌더러 프로세스가 종료되더라도 다른 렌더러 프로세스에는 영향을 미치지 않습니다. Renderer 프로세스는 BrowserWindow 인스턴스를 파괴하여 Main 프로세스에서 종료할 수도 있습니다.

기본적으로 Renderer 프로세스는 창 및 문서 객체 등과 같은 브라우저 API에만 액세스할 수 있습니다. 이는 Renderer 프로세스가 단순히 실행 중인 Chromium 브라우저 인스턴스이기 때문입니다. 그러나 프로세스 및 요구와 같은 Node.js API에 액세스하도록 구성할 수 있습니다.



###2장

Build a Simple Electron.js Project
Now it’s time to get hands-on Electron.js experience! In this tutorial you will be creating a simple desktop application a task list. The goal is to create a desktop application from scratch and run it successfully.

To begin, run the following commands from your preferred parent directory to create a folder for the project, and then change directory into the new folder:

mkdir my-electron-app
cd my-electron-app

Because an Electron.js app is, at heart, a Node.js application running web pages, you’ll need initialize the app and create a package.json file by running the following command:

npm init -y
Next, create the application home page by creating an index.html file at the root of the project folder and add the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Electron App</title>
</head>

<body>
    <h1>Welcome to My Electron App</h1>
</body>

</html>

The HTML code above creates a simple webpage with a title that reads “My Electron App” and an h1 tag in the body with the text “Welcome to My Electron App”.

At this point you have a basic Node.js application. The next step is to convert your app into a desktop application using Electron.js.

Start by installing the Electron.js library. Back in your command prompt, still in your project’s root directory, run the following command:

npm install --save-dev electron
Once the installation is complete, create a new file called main.js. This will be the entry point into the application: it’s the Main process script. This script will do the following:

Create a web page for the application home screen
Load the application home screen when the Electron.js app is booted up
Load the home screen when the app’s icon is clicked if the app’s windows are closed but the app is still running
In your new file, main.js, begin by importing the necessary packages and then creating a function whose job is to create a new web page for the application home screen:

//import from electron 
const { app, BrowserWindow } = require("electron");
const path = require("path");

//load the main window
const loadMainWindow = () => {
    const mainWindow = new BrowserWindow({
        width : 1200, //width of window
        height: 800, //height of window
        webPreferences: {
            nodeIntegration: true
        }
    });

load the `index.html` file
    mainWindow.loadFile(path.join(__dirname, "index.html"));
}

In the code block above, app (the Electron.js application object) and BrowserWindow (the Electron.js module for creating and loading web pages) are imported from the Electron.js package. The path module is also imported, enabling you to work with the project directory.

After the imports, you create the loadMainWindow() function. This function uses the BrowserWindow object to create a new 1200px by 800px browser window that loads the index.html file from the project’s root.

Next, beneath the existing code, add a call to the loadMainWindow() function so that the function is invoked immediately after the app boots up:

app.on("ready", loadMainWindow);

The loadMainWindow() only gets called when the ready event is emitted on the app. The web page needs to wait for this event because some APIs can only be used after this event occurs.

The next step is to take care of an issue on some operating systems where the application still remains active even after all windows have been closed. This often occurs on non-MacOS platforms. To fix this, add the following below the existing code in main.js :

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

This code instructs the app to listen for the window-all-closed event, which is fired when all windows created by the Main process have been closed. It then checks if the platform is MacOS and if not, it explicitly quits the application, ending the Main process and thus terminating the application.

The final step in this file is to ensure that the application boots up when its icon is clicked in the operating system’s application dock when there are no windows open. To achieve this, add the following code at the end of the file:

app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        loadMainWindow();
    }
});

This code listens for the activate event on the app. When the event is emitted, this code checks if there are any windows currently open that belong to the application. If not, the home screen is loaded by calling loadMainWindow() .

That’s it for the main.js file.

Configure the Application
You’ll need to make some changes to your package.json file to ensure that it’s configured correctly to work with Electrion.js.

Open your package.json file. Change the value of the main key to main.js as shown below:

"main": "main.js",
Next, add a start script to the scripts section like below:

"scripts": {
    "start" : "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
 }

Save and close the file. At this time, you can run your new Electron.js application with the following command:

npm start
This will boot up the application and load the home screen window.

Create a Simple Task List System
In order to learn some other features of Electrion.js , you will be creating a bare-bones task list system.

To begin, you’ll add some basic content to your app’s home screen.

Open the index.html file and add the Bootstrap library just below the meta tags in the head section as shown below:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <title>My Electron App</title>
</head>

Next, inside the body element, below the h1 tag, add the highlighted lines to create a two-column layout. The first column will contain the task list:

<body>
    <h1>Welcome to My Electron App</h1>
    <div class="container">
       <div class="row">
           <div class="col-md-6">
               <ul id="list" class="list-group">
                  <li class="list-group-item">Buy Groceries</li>
                  <li class="list-group-item">Cook Meal</li>
               </ul>
           </div>

           <div class="col-md-6">
           </div>
       </div>
    </div>
</body>

If the app is currently running, close it by pressing Ctrl+C in your command prompt and restart it by running npm start .

Add a New Item to the Task List
In your index.html file, add a form input and button element. The user will interact with these elements to add new items to the task list. To add these elements, copy and paste the highlighted lines into the second column of the two-column grid:

<body>
    <h1>Welcome to My Electron App</h1>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <ul id="list" class="list-group">
                  <li class="list-group-item">Buy Groceries</li>
                  <li class="list-group-item">Cook Meal</li>
                </ul>
            </div>

            <div class="col-md-6">
                <input class="form-control" id="newTask" placeholder="Enter New Task" />
                <br />
                <button type="button" class="btn btn-primary" id="addTask">
                    Add Task
                </button>
            </div>
        </div>
    </div>
</body>

Now, create a new JavaScript file called script.js at the root of the project and import it into the index.html file as shown below:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="script.js"></script>
    <title>My Electron App</title>
</head>

Inside the script.js file, add the following code:

let list = document.getElementById("list");
let newTask = document.getElementById("newTask");

document.getElementById("addTask").addEventListener('click', () => {
    list.insertAdjacentHTML('beforeend', `<li class="list-group-item">${newTask.value}</li>`)
    newTask.value = '';
});

In the code above, a click event handler is added to the button element you added in index.html. When the button is clicked, the value of the input field is inserted into a new <li> element, which is appended to the task list.

Now, quit the application and restart. Try adding a few new items by typing in the input field and clicking the Add Task button.

It works right?!THE POWERR OF FEELIN'

Conclusion
Electron.js is a game-changer in the world of application development as it gives web developers the ability to enter the native application development space with their existing set of skills.

3 장

Paybacks
-High RAM consumption: Electron apps tend to use a minimum of 80 MB of RAM, with lightweight apps in the 130-250 MB range and monsters like Slack sometimes reaching multi-GB values.

-Large storage footprint: Shipping with a full Chromium runtime, you can expect most Electron apps to consume at least 150 MB of storage.

-Slow: Some Electron apps are definitely slow, but that can depend on many factors. Overuse of animations, for example, can substantially increase the CPU usage and thus make the app feel slower. Did you notice that most desktop apps that feel snappy don’t include any animation? Just because you can with Electron, doesn’t mean you should.

-Lack of native UI/UX: Electron renders webpages and not native controls. On one hand, that gives complete freedom to designers, but on the other, the app looks different from the “native” ones. Unsurprisingly, this complaint usually comes from macOS users, where a single “native” framework exists: Cocoa. Due to the fragmentation of GUI frameworks on other platforms (especially Windows), non-macOS users are usually more tolerant of apps not sharing the same look and feel.

-Worse security: Compared to the average website running on your web browser, Electron apps are incredibly more powerful (and dangerous) thanks to the NodeJS integration. If not properly configured, web pages running inside Electron can gain access to the entire system, which is particularly dangerous when displaying third-party websites. Luckily, it doesn’t have to be that way, as Electron provides Context Isolation to shield the renderer from NodeJS APIs. Moreover, some believe that the NPM ecosystem is less secure than other counterparts.

좋은 웹페이지 즐겨찾기