[Vue3/Typescript] 가위 바위 보 게임 만들기 – 5. Electron 적용

개발을 하다 보면 만들어 놓은 프로그램을 데스크앱으로 만드면 좋을 거 같다는 생각이 드는데 이걸 도와주는 프레임워크가 있다.

https://www.electronjs.org/

위의 프레임워크로 굴직한 프로그램들이 많이 제작되었다.

사용법이 관심이 든다면 한 번쯤 https://www.electronjs.org/docs/latest/

공식 문서를 읽어보면 좋을거 같다(필자도 다 보진 않았다 ㅎㅎ).

여기선 간단하게 여지껏 만든 프로젝트를 데스크앱으로 어떻게 변환하는지 알아보겠다.

● package.json

main, author, build 속성을 추가하였다. 그리고 concurrently, cross-env, electron, electron-builder라이브러리를 추가하였다. 

추가된 scripts에서 우리가 직접 실행해볼것은 electron:dev, app:build이다. electron:dev 개발용으로 콘솔로그가 활성화되어서 개발 시에 확인하기 좋다. 그리고 모든 게 확인이 되었다면 app:build로 앱을 만들면 된다.

그다음으로 위와 같이 루트에 폴더와 파일을 만든다.

● preload.ts

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener("DOMContentLoaded", () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector);
    if (element) element.innerText = text;
  };

  for (const dependency of ["chrome", "node", "electron"]) {
    replaceText(`${dependency}-version`, process.versions[dependency]);
  }
});

● electron.ts

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

const isDev = process.env.IS_DEV == "true" ? true : false;

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 900,
    webPreferences: {
      preload: path.join(__dirname, "preload.ts"),
      nodeIntegration: true,
    },
  });

  // and load the index.html of the app.
  // win.loadFile("index.html");
  mainWindow.loadURL(
    isDev
      ? "http://localhost:4000"
      : `file://${path.join(__dirname, "../dist/index.html")}`
  );
  // Open the DevTools.
  if (isDev) {
    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", function () {
    // 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();
  }
});

 

앱의 크기를 800*900으로 설정하였는데, 위의 값을 수정해서 앱의 크기를 바꿀 수 있다.

● vite.config.ts

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

// https://vitejs.dev/config/
export default defineConfig({
  base: process.env.ELECTRON == "true" ? "./" : "/vue3-rock-paper-scissors/",
  server: {
    port: 4000,
    proxy: {
      "/sample": {
        target: "https://jsonplaceholder.typicode.com",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/sample/, ""),
      },
    },
  },
  resolve: {
    alias: {
      "~/": `${resolve(__dirname, "./src")}/`,
      vue: "vue/dist/vue.esm-bundler.js",
    },
  },
  plugins: [vue()],
});

 

base: process.env.ELECTRON == “true” ? “./” : “/vue3-rock-paper-scissors/”,
이 부분이 수정이 되었다. 앱으로 빌드할 때 경로를 “./”로 바꿔줘야 화면이 나와서 여기서 설정을 해줘야 한다.

이제빌드를 하면

dist_electron이란 폴더에 위와 같은 파일이 생긴다. MyApp-0.0.0-arm64.dmg 파일은 설치파일이고 mac-arm64 폴더에 들어가면 실행 파일을 볼 수 있다.

맥에서 빌드를 해서 맥용으로 나왔다. 윈도 환경이라면 윈도용 파일로 만들어질 것이다.

여기서 ‘[Vue3/Typescript] 가위 바위 보 게임 만들기’편은 마무리하겠다.

 


소스

https://github.com/junseongday/vue3-rock-paper-scissors

Leave A Reply

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다