전체목차 : https://gauryan.tistory.com/214

 

이제, 본격적으로 시작해봅시다. 우선, https://code.visualstudio.com/ 에서 Visual Studio Code를 다운로드하여 설치합니다. 에디터는 자신이 원하는 다른 것(IntelliJ IDEA, Atom, Eclipse 등)으로 하셔도 괜찮습니다.

 

Vue.js 3에 관련된 확장프로그램은 아래와 같이 설치하였습니다.

 

https://nodejs.org/ 에서 Node.js를 다운로드하여 설치한다. 

 

node.js 설치를 마치고 다음처럼 설치가 잘 되었는지 확인해보자~! 저는 LTS버전을 설치했는데, 아무거나 설치하셔도 됩니다.

Vue 3 프로젝트를 생성합니다. > npm init vue@latest

Vue Router, Pinia, ESLint 등을 선택하였다.

이제, 웹브라우저에 http://localhost:5173 으로 접속하면, 아래와 같은 화면이 나오게 됩니다. 그러면 일단 성공~!!!

프로젝트 폴더에서 VS Code를 실행해봅니다. 아래처럼...

프로젝트의 디렉토리 구조를 유심히 봐주시고, 어떤 파일들이 있는지도 눈여겨 봅시다. 각 디렉토리와 파일에 대해서는 다음 글에서 설명하도록 하겠습니다.

 

ESLint 설정을 위해서, View 메뉴의 Command Palette 를 선택(단축키: ctrl+shift+p)하고, Open User Settings (JSON)을 입력한다. 그러면, settings.json 파일이 열리며, 아래 내용을 추가해준다.

{
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
      "source.fixAll": true
  },
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
  "javascript.format.placeOpenBraceOnNewLineForControlBlocks": false,
  "javascript.format.placeOpenBraceOnNewLineForFunctions": false
}

 

.eslintrc.js 파일에는 rules 안에 다음을 추가해준다. 개인적으로는 세미콜론을 사용하는 것을 선호하며, Camel Case 를 사용하기도 하지만, Snake Case 도 함께 사용한다.

rules: {
..
  // 'semi': [2, 'always'],
  'semi': 'off',
  'camelcase': 'off',
  "prettier/prettier": [
    "error",
    {
      "endOfLine": "auto",
      "printWidth": 160,
    }
  ],
..
}

 

File > Preferences > Configure User Snippets > New Global Snippets File... 메뉴를 선택하고, vue3 를 입력한다. 그리고, vue3.code-snippets 파일에 다음을 입력해준다. 이렇게 하면, vue 파일을 생성하고, 에디터에서 vue3 라고 입력하면 미리 입력된 코드조각을 쉽게 넣을 수 있다. 자신의 코드스타일에 맞추어서 바꾸는 것도 괜찮을 듯 한다.

	"Initialize Vue3": {
		"scope": "vue",
		"prefix": "vue3",
		"body": [
			"<style scoped>",
			"</style>",
			"",
			"<template>",
			"</template>",
			"",
			"<script setup>",
			"// import { ref } from 'vue'",
			"</script>",
			""
		],
		"description": "Initialize Vue3"
	}

 

src/components/HelloWorld.vue 파일을 삭제하고, src/assets/logo.png 파일도 삭제합니다. 그리고, src/App.vue 파일을 아래처럼 수정해주세요. ~.vue 파일은 뷰컴포넌트를 의미합니다. 뷰컴포넌트는 script, template, style 로 구성됩니다.

<style scoped>
h1 {
  text-align: center;
}
</style>

<template>
  <h1>Hello, World~!</h1>
</template>

<script setup></script>

이렇게 저장하고, 웹브라우저를 보면 아래처럼 Hello, World~! 출력될 거에요. 앞으로 우리는 App.vue 에서 대부분의 작업을 할 예정입니다.

 

Bootstrap 도 설치해봅시다.

> npm i bootstrap
> npm i @popperjs/core

 

Bootstrap 을 적용하려면, main.js 파일을 열어서 아래 내용을 추가한다.

import "bootstrap/dist/css/bootstrap.css";
import "bootstrap/dist/js/bootstrap.js";

또는, App.vue 파일에서 <style>바로 아랫줄에 bootstrap.css파일을 임포트하고, <script> 아랫줄에는 bootstrap.js 파일을 임포트해준다. 아무래도, main.js 파일에 적용하는 것이 더 간편할 듯 하다.

<script setup>
import "bootstrap/dist/js/bootstrap.js";
...


<style scoped>
@import "bootstrap/dist/css/bootstrap.css";
...

그리고, 다시 src/App.vue 파일을 아래처럼 수정해본다.

<script setup></script>

<template>
<div>
  <h1>Hello, World~!</h1>
  <button class="btn btn-primary">부트스트랩 버튼</button>
</div>
</template>

<style scoped>
div {
  text-align: center;
}
</style>

 

이제, 진짜 마지막 화면입니다. 부트스트랩 디자인 버튼을 하나 만들었는데, 잘 나오네요.

 

마지막으로, 크롬 확장프로그램을 설치할거에요. chrome 웹 스토어에서 vue를 검색하여, Vue.js devtools를 설치합니다. 크롬에서 Vue 디버깅할때 아주 유용하다고 합니다.

 

 

 

Vue.js 3 의 기본적인 사용법을 설명합니다. Vue2 에서 Options API를 통해 개발했다면, Vue3 에서는 Composion API로 개발을 하게 됩니다. 보통, Composion API로 만들게 되면, Setup() 함수에 구현을 하는데요, 여기서는 Setup()함수를 사용하지 않습니다. 대신, script 태그 선언시에 setup 옵션을 추가합니다. 이렇게 하면 코드를 더욱 간결하게 작성할 수 있습니다.

 

  • 개발환경 구성과 프로젝트 생성 (Hello World)
  • 폴더와 파일에 대한 설명
  • 뷰 데이터와 함수
  • 데이터 바인딩
  • 이벤트
  • 데이터 양방향 바인딩
  • Computed 속성
  • Watch 속성
  • 클래스&스타일 바인딩
  • v-if와 v-show
  • v-for 리스트렌더링
  • 여러개의 Vue 인스턴스 사용하기
  • Vue 컴포넌트
  • 뷰 라우터 ( yarn add "vue-router@^4.0.0" )
  • 싱글 파일 콤포넌트
  • 자식 컴포넌트에 데이터 보내기
  • 부모 컴포넌트로 데이터 보내기
  • 슬롯
  • 뷰 인스턴스 라이프사이클
  • 미니 프로젝트 (단어장 1)
  • 미니 프로젝트 (단어장 2)
  • Context

 

path 를 "/abc/:id" 와 같은 식으로 정의하고, "/abc/1" 페이지에서 "/abc/2" 페이지를 호출하려는 경우에 페이지가 리로드되지 않는다. 이런 경우, 아래와 같이 해주면 해결될 것이다.

 

<template>
  <router-view :key="route.fullPath" />
</template>

<script setup>
import { useRoute } from "vue-router";
const route = useRoute();
</script>

 

Vite + Vue3 + Javascript + Electron 를 이용하여 데스크탑앱 개발 환경을 설정해보자. 참고했던 문서에서는 Typescript 로 되어 있었는데, 필자는 아직 Javascript를 쓰고 싶다. ^^;


Step 1. Vite 프로젝트 생성하기

> yarn create vite
yarn create v1.22.17
[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: ... vite-project
√ Select a framework: » vue
√ Select a variant: » vue

Scaffolding project in C:\Mattabu\Study\Vue\vite-project...

Done. Now run:

  cd vite-project
  yarn
  yarn dev

Done in 12.26s.

yarn create vite 를 실행하면 프로젝트를 설정하는 프롬프트가 나온다. 프로젝트명을 vite-project로 입력하고 vue 프레임워크를 사용한다고 선택하고 variant도 Javascript( vue )를 사용한다고 선택했다.

 

Step 2. 프로젝트 폴더로 이동한 후에 Electron 모듈 및 종속성 모듈 설치

# 프로젝트 폴더로 이동
> cd vite-project

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

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

 

Step 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 속성 수정/추가

  "scripts": {
    "dev": "vite",
    "build": "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": "cross-env ELECTRON=true vite build",
    "app:build": "yarn build:for:electron && yarn electron:builder"
  },

 

main, license, author 등 속성 추가

{
  "name": "vite-electron-app-test",
  "author": "Gauryan",
  "license": "MIT",
  "version": "0.0.0",
  "main": "electron/electron.js",
  ...
}

 

Step 4. vite.config.js 파일 수정

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

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

 

Step 5. electron/electron.js 파일 생성

// 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();
  }
});

 

Step 6. electron/preload.js 파일 생성

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

 

Step 7. 개발모드 실행 및 빌드

# Run yarn electron:dev to work with electron in development mode.
> yarn electron:dev

# Run yarn app:build to build your electron app.
> yarn app:build

 

Step 8. 참고

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

 

Vite + Vue 3 + electron + TypeScript

A lot of people have been asking how to do electron in vite vue 3 so here it is. Step...

dev.to

https://learnvue.co/2021/05/build-vue-3-desktop-apps-in-just-5-minutes-vite-electron-quick-start-guide/#setting-up-our-electron-main-js

 

Building a Vue 3 Desktop App with Vite and Electron

Level up your Vue development with tutorials for all experience levels!

learnvue.co

 

+ Recent posts