티스토리 뷰

Electron + Vite + Vue3 + Typescript를 이용하여 데스크탑 앱 개발 환경을 설정해보자.

1. Vite 프로젝트 생성

$ yarn create vite
yarn create v1.22.15
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Installed "create-vite@2.7.2" with binaries:
      - create-vite
      - cva
√ Project name: ... sample-project
√ Select a framework: » vue
√ Select a variant: » vue-ts

Scaffolding project in D:\_xshine\work\nodejs\electron\vue3\sam2edit...

Done. Now run:

  cd sample-project
  yarn
  yarn dev

Done in 723.60s.

yarn create vite 를 실행하면 프로젝트를 설정하는 프롬프트가 나온다.

프로젝트명을 sample-project로 입력하고 vue 프레임워크를 사용한다고 선택하고 Typescript( vue-ts )를 사용한다고 선택했다.

2. Electron 모듈 및 종속성 모듈 설치

# electron 모듈 설치
$ yarn add -D concurrently cross-env electron electron-builder wait-on

# 프로젝트 종속성 모듈 설치
$ yarn

3. package.json 파일 수정

build 속성 추가 (electron build에서 자세한 내용 확인할 수 있다.)

"build": {
  "appId": "com.my-website.my-app",
  "productName": "MyApp",
  "copyright": "Copyright © 2019 ${author}",
  "mac": {
    "category": "public.app-category.utilities"
  },
  "nsis": {
    "oneClick": false,
    "allowToChangeInstallationDirectory": true
  },
  "files": [
    "dist/**/*",
    "electron/**/*"
  ],
  "directories": {
    "buildResources": "assets",
    "output": "dist_electron"
  }
}

 

scripts 속성에 script 추가

"scripts": {
  "dev": "vite",
  "build": "vue-tsc --noEmit && vite build",
  "serve": "vite preview",
  "electron": "wait-on tcp:3000 && cross-env IS_DEV=true electron .",
  "electron:pack": "electron-builder --dir",
  "electron:dev": "concurrently -k \"cross-env BROWSER=none yarn dev\" \"yarn electron\"",
  "electron:builder": "electron-builder",
  "build:for:electron": "vue-tsc --noEmit && cross-env ELECTRON=true vite build",
  "app:build": "yarn build:for:electron && yarn electron:builder"
},

 

main 속성 추가

{
    "name": "sample-project",
    "version": "0.0.0",
    "license": "MIT",
    "main": "electron/electron.js"
    ...
  }

4. vite.config.ts 파일 수정

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  base: process.env.ELECTRON=="true" ? './' : ".",
  plugins: [vue()]
})

5. electron/electron.js 파일 생성

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: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    },
  });

  // and load the index.html of the app.
  // win.loadFile("index.html");
  mainWindow.loadURL(
    isDev
      ? 'http://localhost:3000'
      : `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();
  }
});

6. electron/preload.js 파일 생성

// 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])
  }
})

7. 프로젝트 실행 및 빌드

# 개발 모드로 Electron 실행
$ yarn electron:dev

# Electron 앱 빌드
$ yarn app:build

 

참고 : https://dev.to/brojenuel/vite-vue-3-electron-5h4o

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday