Commit 352d2cfc authored by ali's avatar ali

feat: 项目初始化

parent d15fde22
Pipeline #47453 canceled with stages
# http://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
max_line_length = 100
trim_trailing_whitespace = true
node_modules/
buildAssets/icons/
dist/
release/
docs/
.idea/
.vscode/
.github/
{
"root": true,
"parser": "vue-eslint-parser",
"parserOptions": {
"parser": "@typescript-eslint/parser",
"sourceType": "module",
"ecmaVersion": 2022,
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"node": true,
"es6": true
},
"extends": ["standard", "plugin:vue/vue3-recommended", "prettier"],
"globals": {
"__static": true
},
"plugins": ["vue"],
"rules": {
"arrow-parens": 0,
"generator-star-spacing": 0,
"no-case-declarations": 0,
"array-callback-return": 0,
"no-trailing-spaces": 1,
"no-control-regex": 0,
"no-useless-constructor": 0,
"node/no-deprecated-api": 0
}
}
# .gitignore for NodeJS Projects
# ---------- Start of common ignore files
# Node artifact files
node_modules/
# Log files
*.log
# dotenv environment variables file
.env
# JetBrains IDEs
.idea/
*.iml
# Visual Studio Code IDE
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
# Generated by MacOS
.DS_Store
.AppleDouble
.LSOverride
# Generated by Windows
Thumbs.db
[Dd]esktop.ini
$RECYCLE.BIN/
# Applications
*.app
*.pkg
*.dmg
*.exe
*.war
*.deb
# Large media files
*.mp4
*.tiff
*.avi
*.flv
*.mov
*.wmv
# ---------- End of common ignore files
# Project Files
dist/
release/
tests/results/
npm-debug.log
npm-debug.log.*
vite-plugin-electron.log
# Lock files
*-lock.json
# IDEs
.idea/
.vscode/
# Project files
.github/
buildAssets/icons/
dist/
release/
{
"useTabs": false,
"semi": false,
"vueIndentScriptAndStyle": false,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "none",
"bracketSpacing": true,
"bracketSameLine": false,
"jsxSingleQuote": false,
"arrowParens": "always",
"insertPragma": false,
"requirePragma": false,
"proseWrap": "never",
"htmlWhitespaceSensitivity": "strict",
"endOfLine": "lf"
}
{
"workbench.settings.useSplitJSON": true,
"eslint.codeActionsOnSave.rules": null,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript"
],
"eslint.workingDirectories": [
{
"mode": "auto"
}
],
"emmet.syntaxProfiles": {},
"files.autoSave": "afterDelay",
"editor.wordWrap": "on",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.tabSize": 2
}
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at https://jooy2.com/contact. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
MIT License
Copyright (c) 2022-2023 jooy2 <jooy2.contact@gmail.com> (https://jooy2.com).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
<div align="center">
![vutron-logo](src/renderer/public/images/vutron-logo.webp)
---
쉽고 빠르게 시작하는 **[Vite](https://vitejs.dev)** + **[Vue 3](https://vuejs.org)** + **[Electron](https://www.electronjs.org)** 템플릿
[![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jooy2/vutron/blob/master/LICENSE) ![Programming Language Usage](https://img.shields.io/github/languages/top/jooy2/vutron) ![github repo size](https://img.shields.io/github/repo-size/jooy2/vutron) ![Stars](https://img.shields.io/github/stars/jooy2/vutron?style=social) ![Commit Count](https://img.shields.io/github/commit-activity/y/jooy2/vutron) ![Line Count](https://img.shields.io/tokei/lines/github/jooy2/vutron) [![Followers](https://img.shields.io/github/followers/jooy2?style=social)](https://github.com/jooy2)
![vutron-logo](.github/resources/vutron-sample.webp)
[English](https://github.com/jooy2/vutron/blob/master/README.md) · **한국어** · [简体中文](https://github.com/jooy2/vutron/blob/master/README.zh-CN.md)
**Vutron** 템플릿은 `Electron`으로 사전 설정 된 크로스 플랫폼 데스크톱 앱입니다. 이 프로젝트는 `Vue 3`을 사용하여 적은 노력으로 빠른 빌드를 가능하게 해줍니다.
</div>
## 사용상의 이점
- ✅ 복잡한 사전 설정 없이도 즉시 빌드할 수 있어 빠른 프로젝트 개발이 가능합니다.
- ✅ 최신 `Vue``Electron` 및 여러 모듈에 대해 신속하게 대응하여 유지 관리되고 있습니다.
- ✅ 레이아웃, 데이터 상태 관리와 같은 다양한 사전 구성에 대해 걱정할 필요가 없습니다.
## 주요 기능
- ⚡️ 핫 리로드 기능을 통한 빠른 개발
- ⚡️ 크로스 플랫폼 개발 및 빌드 지원
- ⚡️ 자동화된 GUI 테스팅 지원
- ⚡️ TypeScript 지원
- ⚡️ 다국어 지원
- ⚡️ 테마 지원 (다크 & 라이트)
- ⚡️ 기본적인 레이아웃 관리
- ⚡️ Pinia 스토어를 활용한 글로벌 상태 관리
- ⚡️ GitHub 커뮤니티와 공식 문서를 통한 프로젝트 기술지원
## [문서 (설치 및 시작하기)](https://vutron.jooy2.com/installation-and-build/getting-started)
자세한 설치 방법이나 기본적인 템플릿 사용 방법에 대한 전체 문서를 참고하려면 다음 문서 페이지를 방문하세요: https://vutron.jooy2.com/installation-and-build/getting-started
## 기여
[GitHub Issue](https://github.com/jooy2/vutron/issues) 페이지를 통해 문제를 보고할 수 있습니다. 또한 자주 사용될 만한 기능이나 버그 수정에 대해 Pull Request를 보내주실 수 있습니다.
## 라이선스
Copyright © 2022-2023 [Jooy2](https://jooy2.com) <[jooy2.contact@gmail.com](mailto:jooy2.contact@gmail.com)> Released under the MIT license.
<div align="center">
![vutron-logo](src/renderer/public/images/vutron-logo.webp)
---
Quick Start Templates for **[Vite](https://vitejs.dev)** + **[Vue 3](https://vuejs.org)** + **[Electron](https://www.electronjs.org)**
[![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jooy2/vutron/blob/master/LICENSE) ![Programming Language Usage](https://img.shields.io/github/languages/top/jooy2/vutron) ![github repo size](https://img.shields.io/github/repo-size/jooy2/vutron) ![Stars](https://img.shields.io/github/stars/jooy2/vutron?style=social) ![Commit Count](https://img.shields.io/github/commit-activity/y/jooy2/vutron) ![Line Count](https://img.shields.io/tokei/lines/github/jooy2/vutron) [![Followers](https://img.shields.io/github/followers/jooy2?style=social)](https://github.com/jooy2)
![vutron-logo](.github/resources/vutron-sample.webp)
**English** · [한국어](https://github.com/jooy2/vutron/blob/master/README.ko-KR.md) · [简体中文](https://github.com/jooy2/vutron/blob/master/README.zh-CN.md)
**Vutron** is a preconfigured template for developing `Electron` cross-platform desktop apps. It uses `Vue 3` and allows you to build a fast development environment with little effort.
</div>
## Advantages of use
- ✅ You can build immediately without any presets, so you can develop quickly.
- ✅ It is being maintained quickly to be compatible with the latest `Vue` and `Electron`, as well as many modules.
- ✅ There is no need to worry about layout and data management by using various additional templates.
## Features
- ⚡️ Rapid development through hot-reload
- ⚡️ Cross-platform development and build support
- ⚡️ Support for automated application testing
- ⚡️ TypeScript support
- ⚡️ Multilingual support
- ⚡️ Support for themes (dark & light)
- ⚡️ Basic layout manager
- ⚡️ Global state management through the Pinia store
- ⚡️ Quick support through the GitHub community and official documentation
## [Documentation (Getting Started)](https://vutron.jooy2.com/installation-and-build/getting-started)
For complete documentation including installation instructions and basic usage, please refer to each item in the link below: https://vutron.jooy2.com/installation-and-build/getting-started
## Contribute
You can report issues on [GitHub Issue](https://github.com/jooy2/vutron/issues). You can also request a pull to fix bugs and add frequently used features.
## License
Copyright © 2022-2023 [Jooy2](https://jooy2.com) <[jooy2.contact@gmail.com](mailto:jooy2.contact@gmail.com)> Released under the MIT license.
<div align="center">
![vutron-logo](src/renderer/public/images/vutron-logo.webp)
---
快速启动模板,适用于 **[Vite](https://vitejs.dev)** + **[Vue 3](https://vuejs.org)** + **[Electron](https://www.electronjs.org)**
[![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jooy2/vutron/blob/master/LICENSE) ![编程语言使用情况](https://img.shields.io/github/languages/top/jooy2/vutron) ![github 仓库大小](https://img.shields.io/github/repo-size/jooy2/vutron) ![Stars(点赞数)](https://img.shields.io/github/stars/jooy2/vutron?style=social) ![提交次数](https://img.shields.io/github/commit-activity/y/jooy2/vutron) ![代码行数](https://img.shields.io/tokei/lines/github/jooy2/vutron) [![Followers(关注者数)](https://img.shields.io/github/followers/jooy2?style=social)](https://github.com/jooy2)
![vutron-logo](.github/resources/vutron-sample.webp)
[English](https://github.com/jooy2/vutron/blob/master/README.md) · [한국어](https://github.com/jooy2/vutron/blob/master/README.ko-KR.md) · **简体中文**
**Vutron** 是一个预配置的模板,用于开发 `Electron` 跨平台桌面应用。它使用 `Vue 3`,使您能够轻松构建快速的开发环境。
</div>
## 使用优势
- ✅ 无需任何预设,即可立即构建,快速开发。
- ✅ 快速维护,与最新的 `Vue``Electron` 以及许多模块兼容。
- ✅ 通过使用各种附加模板,无需担心布局和数据管理。
## 特点
- ⚡️ 通过热重载实现快速开发
- ⚡️ 跨平台开发和构建支持
- ⚡️ 支持自动化应用程序测试
- ⚡️ 支持 TypeScript
- ⚡️ 多语言支持
- ⚡️ 支持主题(暗色和亮色)
- ⚡️ 基本布局管理器
- ⚡️ 通过 Pinia 存储进行全局状态管理
- ⚡️ 通过 GitHub 社区和官方文档提供快速支持
## [文档(入门指南)](https://vutron.jooy2.com/installation-and-build/getting-started)
完整的文档,包括安装说明和基本使用方法,请参阅以下链接的每个项目:https://vutron.jooy2.com/installation-and-build/getting-started
## 贡献
您可以在 [GitHub 问题页面](https://github.com/jooy2/vutron/issues) 上报告问题。您还可以请求拉取请求,修复错误并添加常用功能。
## 许可证
版权所有 © 2022-2023 [Jooy2](https://jooy2.com) <[jooy2.contact@gmail.com](mailto:jooy2.contact@gmail.com)>,根据 MIT 许可证发布。
/* eslint-disable no-template-curly-in-string */
const dotenv = require('dotenv')
const baseConfig = {
productName: 'Vutron',
appId: 'com.vutron.vutron',
asar: true,
extends: null,
compression: 'maximum',
artifactName: '${productName} ${version}_${arch}.${ext}',
directories: {
output: './release/${version}'
},
mac: {
bundleVersion: '1.0',
hardenedRuntime: true,
gatekeeperAssess: false,
notarize: false,
icon: 'buildAssets/icons/icon.icns',
type: 'distribution',
target: [
{
target: 'dmg',
arch: ['x64', 'arm64', 'universal']
}
]
},
dmg: {
contents: [
{
x: 410,
y: 150,
type: 'link',
path: '/Applications'
},
{
x: 130,
y: 150,
type: 'file'
}
],
sign: false
},
win: {
icon: 'buildAssets/icons/icon.ico',
target: [
{
target: 'appx',
arch: 'x64'
},
{
target: 'zip',
arch: 'x64'
},
{
target: 'portable',
arch: 'x64'
},
{
target: 'nsis',
arch: 'x64'
}
]
},
portable: {
artifactName: '${productName} ${version}_${arch} Portable.${ext}'
},
nsis: {
oneClick: true
},
linux: {
executableName: 'vutron',
icon: 'buildAssets/icons',
category: 'Utility',
target: [
{
target: 'snap',
arch: 'x64'
},
{
target: 'deb',
arch: 'x64'
},
{
target: 'rpm',
arch: 'x64'
}
]
}
}
dotenv.config()
baseConfig.copyright = `ⓒ ${new Date().getFullYear()} $\{author}`
baseConfig.files = [
/* A list of files not to be included in the build. */
/*
(Required) The files and folders listed below should not be included in the build.
*/
'dist/**/*',
'!dist/main/index.dev.js',
'!docs/**/*',
'!tests/**/*',
'!release/**/*'
]
// TODO: Notarize for macOS
baseConfig.mac.identity = null
/* if (process.env.MAC_NOTARIZE === 'true') {
baseConfig.afterSign = './buildAssets/builder/notarize.ts'
} else {
baseConfig.mac.identity = null
} */
module.exports = {
...baseConfig
}
# Node artifact files
node_modules/
# VitePress files
dist
dist/*
src/.vitepress/.temp
src/.vitepress/.temp/*
src/.vitepress/cache
src/.vitepress/cache/*
This diff is collapsed.
{
"name": "docs",
"version": "1.0.0",
"scripts": {
"dev": "vitepress dev src",
"build": "vitepress build src",
"serve": "vitepress serve src"
},
"author": "jooy2 <jooy2.contact@gmail.com>",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"vitepress": "^1.0.0-rc.24",
"vitepress-sidebar": "^1.18.0",
"vue": "^3.3.7"
}
}
import { generateSidebar } from 'vitepress-sidebar'
import { name, description, repository } from '../../../package.json'
const capitalizeFirst = (str: string): string => str.charAt(0).toUpperCase() + str.slice(1)
export default {
title: capitalizeFirst(name),
description,
outDir: '../dist',
head: [
['link', { rel: 'icon', href: '/logo.png' }],
['link', { rel: 'shortcut icon', href: '/favicon.ico' }]
],
cleanUrls: true,
themeConfig: {
logo: { src: '/icon.png', width: 24, height: 24 },
search: {
provider: 'local'
},
sidebar: generateSidebar({
documentRootPath: 'src',
collapsed: false,
useTitleFromFileHeading: true,
useTitleFromFrontmatter: true,
sortMenusByFrontmatterOrder: true,
hyphenToSpace: true,
capitalizeEachWords: true,
manualSortFileNameByPriority: [
'installation-and-build',
'project-structures',
'electron-how-to'
]
}),
socialLinks: [{ icon: 'github', link: repository.url.replace('.git', '') }]
}
}
# Main vs Renderer Process
A **Vutron** application is divided into code into a Main process and a Renderer process.
**"Main"** is the code of `src/main` and is mainly the process code handled by Electron. **"Renderer"** is the code of `src/renderer`, mainly for front-end rendering process like Vue.
In general, **NodeJS** scripts cannot be run in the renderer process. Examples include modules that contain APIs used by NodeJS, or native modules of **NodeJS** such as `path` or `net`, `os` or `crypto`.
Preload scripts are run before the renderer is loaded. It creates a bridge to the main process to keep the execution of NodeJS scripts in the renderer area separate and isolated for security reasons.
For secure script execution, it is recommended that the main process executes the Node scripts, and the renderer receives the execution results via messaging. This can be implemented via **IPC communication**.
For more information on this, see the following articles: https://www.electronjs.org/docs/latest/tutorial/ipc
### How to run NodeJS on a renderer?
If you want to skip the security issues and use NodeJS scripts in your renderer, you need to set `nodeIntegration` to `true` in your `vite.config.ts` file.
```javascript
rendererPlugin({
nodeIntegration: true
})
```
For more information on this, see the following articles: https://github.com/electron-vite/vite-plugin-electron-renderer
# Preload Script
The preload script in Electron.js is a secure area designed for communication between the main and renderer processes. It is typically used for **[IPC communication](https://www.electronjs.org/docs/latest/tutorial/ipc)**.
For more information, see the following articles https://www.electronjs.org/docs/latest/tutorial/tutorial-preload
For compatibility and security with the latest version of Electron, we do not recommend using the old `electron/remote` module. If you want to utilize system events or Node scripts, it is recommended to do so in the main process, not the renderer.
Vutron's preload script is located in the `src/preload` folder. To create a new IPC communication channel, add the channel name to the following variable to whitelist it for communication.
- `mainAvailChannels`: Send an event from main to renderer. (`window.mainApi.send('channelName'')`)
- `rendererAvailChannels`: Send an event from renderer to main. (`mainWindow.webContents.send('channelName')`)
When sending events from renderer to main, you access the `window.mainApi` object instead of `ipcRenderer.send`. The `mainApi` is the name you set in your Vutron template and can be changed.
Here are the supported functions for mainApi: (To change and modify this, you need to modify `exposeInMainWorld` in `src/preload/index.ts`).
- `send`: Send an event to main.
- `receive`: A listener to receive events sent by main.
- `invoke`: Functions that can send events to main and receive data asynchronously.
---
order: 4
---
# Automated Testing
**Vutron** includes automated testing. The testing framework uses Microsoft's **[Playwright](https://playwright.dev)**.
**Playwright** is optimized for web application testing and has full support for the **Electron** framework. It is simple to install, requires no configuration to start testing immediately, and is cross-platform. You can learn more about **Playwright** here: https://github.com/microsoft/playwright
Only very simple launch and behavioral tests for the template main screen have been implemented in this template. Advanced testing will depend on the scope of your application.
Currently, the test specification file is located in the `tests` directory and the test results file is located in `tests/results`. (The built-in test specification file does not generate a separate results file.)
The Playwright configuration is `playwright.config.ts` in the project root, see the following documentation for more information on this: https://playwright.dev/docs/test-configuration
Once everything is configured, you can run a test with the following command.
```shell
$ npm run test
```
Before running the test, empty the build directory (`dist`) and compile the package for the test.
---
order: 2
---
# Build Configurations
Once the module installation is complete, you can simply build the platform package with the command below.
```shell
# For Windows (.exe, .appx)
$ npm run build:win
# For macOS (.dmg)
$ npm run build:mac
# For Linux (.rpm, .deb, .snap)
$ npm run build:linux
# All platform (.exe, .appx, .dmg, .rpm, .deb, .snap) - see below description
$ npm run build:all
```
The built packages can be found in `release/{version}` location.
For more information, please refer to the following article: https://webpack.electron.build/dependency-management#installing-native-node-modules
## What do I need to do for a multi-platform build?
To create a package for each OS, you must build it on the same OS. For example, a package for macOS must be built on a macOS machine.
However, you can build packages for Windows, macOS, and Linux all at once on one OS. However, this might require some preparation.
**macOS** is recommended if you want to build multiple platforms simultaneously on one platform. Because it can be configured with just a few very simple settings.
You can perform multi-platform builds at once with the following command. Alternatively, you can just do it for the OS you want via the individual build commands above.
```shell
$ npm run build:all
```
`Multipass` configuration may be required for Linux builds. Learn more about `Multipass` through the following link: https://multipass.run
To learn more about multiplatform builds, see the following articles: https://www.electron.build/multi-platform-build
## Reduce bundle size by excluding development files
You can exclude files you don't need at build time by adding a file pattern to the files property of `buildAssets/builder/config.ts`. This will save bundle capacity.
Below is an unnecessary `node_modules` file pattern that can further save bundles. Depending on the project, using the rules below may cause problems, so please review it before using.
```json
[
"!**/.*",
"!**/node_modules/**/{CONTRIBUTORS,CNAME,AUTHOR,TODO,CONTRIBUTING,COPYING,INSTALL,NEWS,PORTING,Makefile,htdocs,CHANGELOG,ChangeLog,changelog,README,Readme,readme,test,sample,example,demo,composer.json,tsconfig.json,jsdoc.json,tslint.json,typings.json,gulpfile,bower.json,package-lock,Gruntfile,CMakeLists,karma.conf,yarn.lock}*",
"!**/node_modules/**/{man,benchmark,node_modules,spec,cmake,browser,vagrant,doxy*,bin,obj,obj.target,example,examples,test,tests,doc,docs,msvc,Xcode,CVS,RCS,SCCS}{,/**/*}",
"!**/node_modules/**/*.{conf,png,pc,coffee,txt,spec.js,ts,js.flow,html,def,jst,xml,ico,in,ac,sln,dsp,dsw,cmd,vcproj,vcxproj,vcxproj.filters,pdb,exp,obj,lib,map,md,sh,gypi,gyp,h,cpp,yml,log,tlog,Makefile,mk,c,cc,rc,xcodeproj,xcconfig,d.ts,yaml,hpp}",
"!**/node_modules/**/node-v*-x64{,/**/*}",
"!**/node_modules/bluebird/js/browser{,/**/*}",
"!**/node_modules/bluebird/js/browser{,/**/*}",
"!**/node_modules/source-map/dist{,/**/*}",
"!**/node_modules/lodash/fp{,/**/*}",
"!**/node_modules/async/!(dist|package.json)",
"!**/node_modules/async/internal{,/**/*}",
"!**/node_modules/ajv/dist{,/**/*}",
"!**/node_modules/ajv/scripts{,/**/*}",
"!**/node_modules/node-pre-gyp/!(lib|package.json)",
"!**/node_modules/node-pre-gyp/lib/!(util|pre-binding.js|node-pre-gyp.js)",
"!**/node_modules/node-pre-gyp/lib/util/!(versioning.js|abi_crosswalk.json)",
"!**/node_modules/source-map-support/browser-source-map-support.js",
"!**/node_modules/json-schema/!(package.json|lib)"
]
```
## Build settings for projects that use Native Node modules
For projects that use the **Native Node Module**, add the following script to your `package.json`: When installing dependencies, `electron-builder` will take care of any modules that require rebuilding.
```json
{
"scripts": {
"postinstall": "electron-builder install-app-deps"
}
}
```
---
order: 1
---
# Getting Started
## Clone project
### Method 1: `npm init` (Recommend)
You can easily clone a repository with just the npm command.
```shell
$ npm init vutron
```
The above method will not create unnecessary documentation and `.github` related files for your project.
### Method 2: Use this template
Click **[Use this template](https://github.com/jooy2/vutron/generate)** to instantly create your own project.
This method creates a repository on GitHub immediately, but you will need to clone the project locally before you can use it.
### Method 3: Clone this repository
Clone this repo using below command. This method is suitable for direct contributions to the Vutron repository.
```shell
$ git clone https://github.com/jooy2/vutron <PROJECT_NAME>
```
## Installation
After cloning the project, run the following command in the terminal:
```shell
# via npm
$ npm i
# via yarn (https://yarnpkg.com)
$ yarn install
# via pnpm (https://pnpm.io)
$ pnpm i
```
## Run in development environment
Applications in the development environment run through **[Vite](https://vitejs.dev)**.
```shell
$ npm run dev
```
If your application doesn't appear after running command line commands, you may need to review if the default port is being used by another app.
Vite uses port `5173` by default.
---
order: 5
---
# Manage Local Documentation
Documents from `Vutron` can be viewed in the local environment through the `VitePress` viewer.
This function works only when the entire project is cloned. If you created the project with `npm init vutron`, the `docs` folder is not included.
## Installation
Everything in the instructions below should be done in the `docs` folder.
```shell
$ cd docs
```
Install the relevant packages using the following commands:
```shell
# via npm
$ npm i
# via yarn (https://yarnpkg.com)
$ yarn install
# via pnpm (https://pnpm.io)
$ pnpm i
```
You can run the local server where the documents are hosted via the command below.
```shell
$ npm run dev
```
---
title: NPM Scripts
order: 3
---
# Npm Scripts
> $ npm run %SCRIPT_NAME%
## General
| Script Name | Description |
| --- | --- |
| `dev` | Start Electron as a development environment |
| `dev:debug` | Start Electron as a development environment (with vite debug) |
| `dev:debug:force` | Start Electron as a development environment (with vite debug + clean vite cache) |
| `build:pre` | Commands commonly run at build time. This script does not need to be run separately. |
| `build` | Build the package for the current operating system. |
| `build:all` | Build a specified package for the entire operating system (Requires cross-platform build configuration) |
| `build:dir` | `electron-builder` directory build |
| `build:mac` | Build preconfigured packages for macOS |
| `build:linux` | Build preconfigured packages for Linux |
| `build:win` | Build preconfigured packages for Windows |
| `lint` | ESLint code inspection. It does not modify the code. |
| `lint:fix` | ESLint code inspection. Use auto-fix to fix your code. |
| `format` | Prettier code inspection. It does not modify the code. |
| `format:fix` | Prettier code inspection. Use auto-fix to fix your code. |
| `test` | Build a package for testing and run tests against the test specification file. |
## For Documentation
Used only for contributing to project documentation. Must be run from the `docs` directory location.
| Script Name | Description |
| ----------- | ------------------------------------------------------------------ |
| `dev` | Start the local document server. (For development) |
| `build` | Build a local document server. Used only for GitHub page builders. |
| `serve` | Start the local document server. |
# Other Projects
## Looking for Electron templates made with React?
Also check out the `Retron` project, which consists of Vite + React + Material-UI + Electron.
https://github.com/jooy2/retron
## (Deprecated) Looking for `Vutron` with Webpack 5 compiler?
By using the Vite compiler, we achieved our goals of reducing project and bundle size, and improving development environment and build speed.
The old **Vutron** using the Webpack 5 compiler has been split into the repositories below and will end support soon.
https://github.com/jooy2/vutron-webpack
---
order: 2
---
# Pre-configured Components
## Web app frameworks
- [Vite](https://vitejs.dev)
- [Electron](https://www.electronjs.org)
- [Electron Builder](https://www.electron.build)
## Development help tools
- [TypeScript](https://www.typescriptlang.org)
- [ESLint](https://eslint.org)
- [Prettier](https://prettier.io)
## Front-end frameworks (Vue)
- [Vue](https://vuejs.org)
- [Vue-i18n](https://kazupon.github.io/vue-i18n)
- [Vue-router](https://router.vuejs.org)
- [Pinia](https://pinia.vuejs.org)
## Design frameworks
- [Vuetify](https://vuetifyjs.com)
## Testing
- [Playwright](https://playwright.dev)
---
order: 1
---
# Project Structure
```
/
├─ .github - GitHub files (only used for Vutron GitHub project contributions)
│ └─ ISSUE_TEMPLATE/
│ └─ resources/ - GitHub resources used for README.md, etc.
│ └─ workflows/ - GitHub workflows definition
│ └─ dependabot.yml
│ └─ FUNDING.yml
├─ .vscode - Common project configuration files used by Visual Studio Code IDE
├─ buildAssets/ - Package resource (icon, logo, etc.) file used for Electron build
│ └─ builder/
│ │ │ └─ config.ts - `electron-builder` dynamic configuration file
│ └─ icons/
├─ dist/ - Output directory used to build the package
├─ docs/ - Project documents (optionally enabled)
│ └─ .vitepress/
│ │ │ └─ config.mts - VitePress configuration file used for document hosting
│ └─ public/ - Root resource directory for VitePress documentation pages
├─ node_modules/
├─ src/
│ ├─ main/ - Main (Electron) process source code
│ │ ├─ utils/ - Main process utilities
│ │ │ └─ Constants.ts - Main global definition
│ │ │ └─ Menus.ts - Main global menu definition
│ │ └─ index.ts - Main process entry point
│ │ └─ IPCs.ts - Main process ipc handlers definition
│ │ └─ MainRunner.ts - Main process main window processing
│ ├─ preload/ - Preload (Electron-Vue communication bridge) process source code
│ │ └─ index.ts
│ ├─ renderer/ - Renderer (Vue) process source code
│ │ ├─ components/ - Vue components collection
│ │ │ └─ layout/ - Layout components
│ │ ├─ locales/ - Vue i18n language resource file
│ │ ├─ plugins/ - Vue plugin definition
│ │ ├─ public/ - Vue static resources
│ │ │ └─ images/
│ │ ├─ router/ - Vue routing definition
│ │ ├─ screens/ - Vue screen component
│ │ │ └─ ErrorScreen.vue - Screen displayed when renderer process and routing errors occur
│ │ │ └─ MainScreen.vue
│ │ │ └─ SecondScreen.vue - Sample screen
│ │ ├─ store/ - Pinia store (Global state management) definition
│ │ ├─ utils/ - Renderer process utilities
│ │ ├─ App.vue - Vue app's root component
│ │ ├─ index.html - Root static index loaded by Electron renderer process
│ └─ └─ main.ts - Renderer process entry point
├─ tests/ - Application test configuration
│ └─ app.spec.ts - Test file specification
├─ .editorconfig - Editor recommended configuration file for IDE
├─ .eslintignore - List of files to be ignored by ESLint
├─ .eslintrc.json - ESLint rule configurations
├─ .gitignore - List of files to not upload to Git
├─ .prettierignore - List of files to disable Prettier file formatting
├─ .prettierrc - Prettier rule configurations
├─ CODE_OF_CONDUCT.md - Files used only on GitHub
├─ LICENSE - Project license file
├─ package.json - NodeJS package configurations
├─ package-lock.json
├─ playwright.config.ts - Playwright test rules configurations
├─ tsconfig.json - TypeScript configurations
├─ tsconfig.node.json - TypeScript configurations
├─ vite.config.ts - Vite compiler build configurations
└─ README.md - Files used only on GitHub
```
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/.vitepress/config.mts", "package.json"]
}
This diff is collapsed.
{
"name": "laipic",
"version": "1.0.0",
"description": "Quick Start Templates for Vite + Vue 3 + Electron",
"homepage": "https://vutron.jooy2.com",
"author": "jooy2 <jooy2.contact@gmail.com>",
"license": "MIT",
"main": "dist/main/index.js",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/jooy2/vutron.git"
},
"bugs": {
"url": "https://github.com/jooy2/vutron/issues"
},
"scripts": {
"serve": "cross-env ELECTRON_ENABLE_LOGGING=true vite",
"serve:debug": "vite -d",
"serve:debug:force": "vite -d --force",
"build": "npm run build:pre && electron-builder --config=buildAssets/builder/config.js",
"build:pre": "npm run format:fix && vue-tsc --noEmit && vite build",
"build:all": "npm run build:pre && electron-builder --config=buildAssets/builder/config.js -wml",
"build:dir": "npm run build:pre && electron-builder --config=buildAssets/builder/config.js --dir",
"build:mac": "npm run build:pre && CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --config=buildAssets/builder/config.js --mac",
"build:linux": "npm run build:pre && electron-builder --config=buildAssets/builder/config.js --linux",
"build:win": "npm run build:pre && electron-builder --config=buildAssets/builder/config.js --windows",
"lint": "eslint --ext .js,.ts,.vue -f ./node_modules/eslint-friendly-formatter src",
"lint:fix": "eslint --ext .js,.ts,.vue -f ./node_modules/eslint-friendly-formatter --fix src",
"format": "prettier .",
"format:fix": "prettier . --write",
"test": "npm run build:pre && xvfb-maybe -- playwright test"
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"pinia": "^2.1.7",
"vue": "^3.3.7",
"vue-i18n": "^9.6.2",
"vue-router": "^4.2.5",
"vuetify": "^3.3.23"
},
"devDependencies": {
"@mdi/font": "^7.3.67",
"@playwright/test": "^1.39.0",
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",
"@vitejs/plugin-vue": "^4.4.0",
"@vitejs/plugin-vue-jsx": "^3.0.2",
"cross-env": "^7.0.3",
"dotenv": "^16.3.1",
"electron": "^27.0.2",
"electron-builder": "^24.6.4",
"electron-extension-installer": "^1.2.0",
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"eslint-config-standard": "^17.1.0",
"eslint-friendly-formatter": "^4.0.1",
"eslint-plugin-import": "^2.29.0",
"eslint-plugin-n": "^16.2.0",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-vue": "^9.18.1",
"playwright": "^1.39.0",
"prettier": "^3.0.3",
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-plugin-electron": "^0.14.1",
"vite-plugin-electron-renderer": "^0.14.5",
"vite-plugin-eslint": "^1.8.1",
"vite-plugin-vuetify": "^1.0.2",
"vue-eslint-parser": "^9.3.2",
"vue-tsc": "^1.8.22",
"xvfb-maybe": "^0.2.1"
}
}
\ No newline at end of file
import { defineConfig } from '@playwright/test'
export default defineConfig({
outputDir: 'tests/results',
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
timeout: 60000,
expect: {
timeout: 10000
}
})
import { BrowserWindow, ipcMain, shell } from 'electron'
import Constants from './utils/Constants'
/*
* IPC Communications
* */
export default class IPCs {
static initialize(window: BrowserWindow): void {
// Get application version
ipcMain.on('msgRequestGetVersion', () => {
window.webContents.send('msgReceivedVersion', Constants.APP_VERSION)
})
// Open url via web browser
ipcMain.on('msgOpenExternalLink', async (event, url: string) => {
await shell.openExternal(url)
})
}
}
import { app, BrowserWindow, RenderProcessGoneDetails } from 'electron'
import Constants from './utils/Constants'
import IPCs from './IPCs'
const exitApp = (mainWindow: BrowserWindow): void => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.hide()
}
mainWindow.destroy()
app.exit()
}
export const createMainWindow = async (mainWindow: BrowserWindow): Promise<BrowserWindow> => {
mainWindow = new BrowserWindow({
title: Constants.APP_NAME,
show: false,
width: Constants.IS_DEV_ENV ? 1500 : 1200,
height: 650,
useContentSize: true,
webPreferences: Constants.DEFAULT_WEB_PREFERENCES
})
mainWindow.setMenu(null)
mainWindow.on('close', (event: Event): void => {
event.preventDefault()
exitApp(mainWindow)
})
mainWindow.webContents.on('did-frame-finish-load', (): void => {
if (Constants.IS_DEV_ENV) {
mainWindow.webContents.openDevTools()
}
})
mainWindow.once('ready-to-show', (): void => {
mainWindow.setAlwaysOnTop(true)
mainWindow.show()
mainWindow.focus()
mainWindow.setAlwaysOnTop(false)
})
if (Constants.IS_DEV_ENV) {
await mainWindow.loadURL(Constants.APP_INDEX_URL_DEV)
} else {
await mainWindow.loadFile(Constants.APP_INDEX_URL_PROD)
}
// Initialize IPC Communication
IPCs.initialize(mainWindow)
return mainWindow
}
export const createErrorWindow = async (
errorWindow: BrowserWindow,
mainWindow: BrowserWindow,
details?: RenderProcessGoneDetails
): Promise<BrowserWindow> => {
if (!Constants.IS_DEV_ENV) {
mainWindow?.hide()
}
errorWindow = new BrowserWindow({
title: Constants.APP_NAME,
show: false,
resizable: Constants.IS_DEV_ENV,
webPreferences: Constants.DEFAULT_WEB_PREFERENCES
})
errorWindow.setMenu(null)
if (Constants.IS_DEV_ENV) {
await errorWindow.loadURL(`${Constants.APP_INDEX_URL_DEV}#/error`)
} else {
await errorWindow.loadFile(Constants.APP_INDEX_URL_PROD, { hash: 'error' })
}
errorWindow.on('ready-to-show', (): void => {
if (!Constants.IS_DEV_ENV && mainWindow && !mainWindow.isDestroyed()) {
mainWindow.destroy()
}
errorWindow.show()
errorWindow.focus()
})
errorWindow.webContents.on('did-frame-finish-load', (): void => {
if (Constants.IS_DEV_ENV) {
errorWindow.webContents.openDevTools()
}
})
return errorWindow
}
// Warning: This file is only used in the development environment
// and is removed at build time.
// Do not edit the file unless necessary.
import { installExtension, VUEJS_DEVTOOLS } from 'electron-extension-installer'
installExtension(VUEJS_DEVTOOLS, {
loadExtensionOptions: {
allowFileAccess: true
}
})
import { app, WebContents, RenderProcessGoneDetails } from 'electron'
import Constants from './utils/Constants'
import { createErrorWindow, createMainWindow } from './MainRunner'
import { macOSDisableDefaultMenuItem } from './utils/Menus'
let mainWindow
let errorWindow
app.on('ready', async () => {
if (Constants.IS_DEV_ENV) {
import('./index.dev')
}
macOSDisableDefaultMenuItem()
mainWindow = createMainWindow(mainWindow)
})
app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow(mainWindow)
}
})
app.on('window-all-closed', () => {
mainWindow = null
errorWindow = null
if (!Constants.IS_MAC) {
app.quit()
}
})
app.on(
'render-process-gone',
(event: Event, webContents: WebContents, details: RenderProcessGoneDetails) => {
errorWindow = createErrorWindow(errorWindow, mainWindow, details)
}
)
process.on('uncaughtException', () => {
errorWindow = createErrorWindow(errorWindow, mainWindow)
})
import { join } from 'path'
import { name, version } from '../../../package.json'
export default class Constants {
// Display app name (uppercase first letter)
static APP_NAME = name.charAt(0).toUpperCase() + name.slice(1)
static APP_VERSION = version
static IS_DEV_ENV = process.env.NODE_ENV === 'development'
static IS_MAC = process.platform === 'darwin'
static DEFAULT_WEB_PREFERENCES = {
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
preload: join(__dirname, '../preload/index.js')
}
static APP_INDEX_URL_DEV = 'http://localhost:5173/index.html'
static APP_INDEX_URL_PROD = join(__dirname, '../index.html')
}
import { systemPreferences } from 'electron'
import Constants from './Constants'
export default class Menus {
static macOSDisableDefaultMenuItem(): void {
if (Constants.IS_MAC) {
systemPreferences.setUserDefault('NSDisabledDictationMenuItem', 'boolean', true)
systemPreferences.setUserDefault('NSDisabledCharacterPaletteMenuItem', 'boolean', true)
}
}
}
export const { macOSDisableDefaultMenuItem } = Menus
import { contextBridge, ipcRenderer } from 'electron'
// Whitelist of valid channels used for IPC communication (Send message from Renderer to Main)
const mainAvailChannels: string[] = ['msgRequestGetVersion', 'msgOpenExternalLink']
const rendererAvailChannels: string[] = ['msgReceivedVersion']
contextBridge.exposeInMainWorld('mainApi', {
send: (channel: string, ...data: any[]): void => {
if (mainAvailChannels.includes(channel)) {
ipcRenderer.send.apply(null, [channel, ...data])
} else {
throw new Error(`Send failed: Unknown ipc channel name: ${channel}`)
}
},
receive: (channel: string, cbFunc: Function): void => {
if (rendererAvailChannels.includes(channel)) {
ipcRenderer.on(channel, (event, ...args) => cbFunc(event, ...args))
} else {
throw new Error(`Receive failed: Unknown ipc channel name: ${channel}`)
}
},
invoke: async (channel: string, ...data: any[]): Promise<any> => {
if (mainAvailChannels.includes(channel)) {
const result = await ipcRenderer.invoke.apply(null, [channel, ...data])
return result
}
throw new Error(`Invoke failed: Unknown ipc channel name: ${channel}`)
}
})
<script setup lang="tsx">
import { DefaultLayout } from '@/renderer/components/layout'
</script>
<template>
<DefaultLayout>
<router-view />
</DefaultLayout>
</template>
<style>
html {
overflow-y: auto !important;
user-select: none;
}
html,
body {
width: 100%;
height: 100%;
}
/* Do not force capitalization of button text */
.v-btn {
text-transform: unset !important;
}
</style>
<script setup lang="tsx">
import HeaderLayout from '@/renderer/components/layout/HeaderLayout.vue'
</script>
<template>
<v-app>
<v-layout>
<HeaderLayout />
<v-main>
<slot />
</v-main>
</v-layout>
</v-app>
</template>
<script setup lang="tsx">
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route: any = useRoute()
const titleKey: string = (route?.meta?.titleKey || 'title.main') as string
const handleRoute = (path: string): void => {
router.push(path)
}
const isCurrentRoute = (path: string): boolean => {
return path === route.path
}
</script>
<template>
<v-app-bar color="primary" density="compact">
<v-app-bar-title>{{ $t(titleKey) }}</v-app-bar-title>
<template #append>
<v-btn
prepend-icon="mdi-home"
variant="text"
:class="{ active: isCurrentRoute('/') }"
@click="handleRoute('/')"
>
{{ $t('title.main') }}
</v-btn>
<v-btn
prepend-icon="mdi-fit-to-screen-outline"
variant="text"
:class="{ active: isCurrentRoute('/second') }"
@click="handleRoute('/second')"
>
{{ $t('title.second') }}
</v-btn>
</template>
</v-app-bar>
</template>
<style scoped>
.v-btn {
opacity: 0.4;
}
.active {
opacity: 1 !important;
}
</style>
import DefaultLayout from '@/renderer/components/layout/DefaultLayout.vue'
import HeaderLayout from '@/renderer/components/layout/HeaderLayout.vue'
export { DefaultLayout, HeaderLayout }
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="app"></div>
</body>
<script type="module" src="./main.ts"></script>
</html>
{
"desc": {
"welcome-title": "Hallo Vutron! Alles ist bereit.",
"welcome-desc": "Sie können jetzt plattformübergreifende Webanwendungen schreiben. Sehen Sie Ihre Änderungen in Echtzeit und erstellen Sie mit einem einzigen Befehl auf mehreren Plattformen. Wenn Sie damit noch nicht vertraut sind, können Sie Hilfe von der Dokumentationsseite unten erhalten oder vorgefertigten Beispielcode ausführen.",
"second-desc": "Auf den zweiten Bildschirm verschoben! Hier gibt es keine!"
},
"title": {
"main": "Hauptbildschirm",
"second": "Zweiter Bildschirm",
"error": "Ein Fehler ist aufgetreten"
},
"menu": {
"change-theme": "Thema wechseln",
"change-language": "Sprache ändern",
"increase-count": "Zählerstand um 1 erhöhen",
"documentation": "dokumentieren",
"github": "Quellcode"
}
}
{
"desc": {
"welcome-title": "Hello Vutron! Everything is ready.",
"welcome-desc": "You can now write cross-platform web applications. See changes in real time and build to multiple platforms with one command. If you're not already familiar with it, you can get help from the documentation page below, or run some pre-written example code.",
"second-desc": "You have moved to the second screen! There is nothing here!"
},
"title": {
"main": "Main Screen",
"second": "Second Screen",
"error": "Unknown Error"
},
"menu": {
"change-theme": "Change Theme",
"change-language": "Change Language",
"increase-count": "Count 1 increment",
"documentation": "Documentation",
"github": "Source Code"
}
}
{
"desc": {
"welcome-title": "Hola Vutron! Todo está listo.",
"welcome-desc": "Ahora puede escribir aplicaciones web multiplataforma. Vea sus cambios en tiempo real y cree en múltiples plataformas con un solo comando. Si aún no está familiarizado con él, puede obtener ayuda en la página de documentación a continuación o ejecutar un código de ejemplo preescrito.",
"second-desc": "¡Movido a la segunda pantalla! ¡Aquí no hay ninguno!"
},
"title": {
"main": "Pantalla principal",
"second": "segunda pantalla",
"error": "Se produjo un error"
},
"menu": {
"change-theme": "cambiar de tema",
"change-language": "cambiar idioma",
"increase-count": "aumentar la cuenta en 1",
"documentation": "documento",
"github": "código fuente"
}
}
{
"desc": {
"welcome-title": "Bonjour Vutron ! Tout est prêt.",
"welcome-desc": "Vous pouvez maintenant écrire des applications Web multiplateformes. Visualisez vos modifications en temps réel et créez sur plusieurs plates-formes avec une seule commande. Si vous ne le connaissez pas encore, vous pouvez obtenir de l'aide sur la page de documentation ci-dessous ou exécuter un exemple de code pré-écrit.",
"second-desc": "Déplacé vers le deuxième écran! Il n'y en a pas ici !"
},
"title": {
"main": "écran principal",
"second": "Deuxième écran",
"error": "Erreur est survenue"
},
"menu": {
"change-theme": "Change le thème",
"change-language": "Changer de langue",
"increase-count": "Augmenter le nombre de 1",
"documentation": "Document",
"github": "Code source"
}
}
{
"desc": {
"welcome-title": "こんにちはVutron! すべての準備が完了しました。",
"welcome-desc": "これで、クロスプラットフォームのWebアプリケーションを作成できます。 変更内容をリアルタイムで確認し、一度のコマンドで複数のプラットフォームにビルドします。 まだ慣れていない場合は、以下のドキュメントページでヘルプを入手するか、事前に作成されたサンプルコードを実行してみてください。",
"second-desc": "2番目の画面に移動しました! ここには何もありません!"
},
"title": {
"main": "メイン画面",
"second": "2番目の画面",
"error": "エラー発生"
},
"menu": {
"change-theme": "テーマの変更",
"change-language": "言語の変更",
"increase-count": "カウント1増加",
"documentation": "文書",
"github": "ソースコード"
}
}
{
"desc": {
"welcome-title": "안녕 Vutron! 모든 준비를 마쳤습니다.",
"welcome-desc": "이제 크로스플랫폼 웹 애플리케이션을 작성할 수 있습니다. 변경사항을 실시간으로 확인하고 한 번의 명령으로 여러 플랫폼으로 빌드하세요. 아직 익숙하지 않다면, 아래 문서 페이지에서 도움을 받아보거나 사전에 작성된 예제 코드를 실행해볼 수 있습니다.",
"second-desc": "두번째 화면으로 이동하였습니다! 여기는 아무 것도 없습니다!"
},
"title": {
"main": "메인 화면",
"second": "두번째 화면",
"error": "에러 발생"
},
"menu": {
"change-theme": "테마 변경",
"change-language": "언어 변경",
"increase-count": "카운트 1 증가",
"documentation": "문서",
"github": "소스코드"
}
}
{
"desc": {
"welcome-title": "Olá Vutron! Tudo está pronto.",
"welcome-desc": "Agora você pode escrever aplicativos da Web de plataforma cruzada. Veja suas alterações em tempo real e crie para várias plataformas com um único comando. Se ainda não estiver familiarizado com ele, você pode obter ajuda na página de documentação abaixo ou executar algum código de exemplo pré-escrito.",
"second-desc": "Movido para a segunda tela! Não há nenhum aqui!"
},
"title": {
"main": "Tela principal",
"second": "Segunda tela",
"error": "Erro desconhecido"
},
"menu": {
"change-theme": "Mudar Tema",
"change-language": "Mudar Idioma",
"increase-count": "Aumentar a contagem em 1",
"documentation": "Documento",
"github": "Código fonte"
}
}
{
"desc": {
"welcome-title": "Привет Vutron! Все готово.",
"welcome-desc": "Теперь вы можете писать кроссплатформенные веб-приложения. Просматривайте свои изменения в режиме реального времени и выполняйте сборку для нескольких платформ с помощью одной команды. Если вы еще не знакомы с ним, вы можете получить помощь на странице документации ниже или запустить предварительно написанный пример кода.",
"second-desc": "Перенесено на второй экран! Здесь их нет!"
},
"title": {
"main": "Главный экран",
"second": "Второй экран",
"error": "Неизвестная ошибка"
},
"menu": {
"change-theme": "Поменять тему",
"change-language": "Изменить язык",
"increase-count": "Увеличить количество на 1",
"documentation": "Документ",
"github": "Исходный код"
}
}
{
"desc": {
"welcome-title": "你好武特龍! 一切都準備好了。",
"welcome-desc": "您現在可以編寫跨平台的 Web 應用程序。 實時查看更改並使用一個命令構建到多個平台。 如果您還不熟悉它,可以從下面的文檔頁面獲得幫助,或者運行一些預先編寫的示例代碼。",
"second-desc": "您已移至第二個屏幕! 這裡什麼都沒有!"
},
"title": {
"main": "主屏幕",
"second": "第二屏",
"error": "未知錯誤"
},
"menu": {
"change-theme": "改變主題",
"change-language": "改變語言",
"increase-count": "計數 1 個增量",
"documentation": "文檔",
"github": "源代碼"
}
}
{
"desc": {
"welcome-title": "你好武特龙! 一切都准备好了。",
"welcome-desc": "您现在可以编写跨平台的 Web 应用程序。 实时查看更改并使用一个命令构建到多个平台。 如果您还不熟悉它,可以从下面的文档页面获得帮助,或者运行一些预先编写的示例代码。",
"second-desc": "您已移至第二个屏幕! 这里什么都没有!"
},
"title": {
"main": "主屏幕",
"second": "第二屏",
"error": "未知错误"
},
"menu": {
"change-theme": "改变主题",
"change-language": "改变语言",
"increase-count": "计数 1 个增量",
"documentation": "文档",
"github": "源代码"
}
}
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from '@/renderer/App.vue'
import router from '@/renderer/router'
import vuetify from '@/renderer/plugins/vuetify'
import i18n from '@/renderer/plugins/i18n'
// Add API key defined in contextBridge to window object type
declare global {
// eslint-disable-next-line no-unused-vars
interface Window {
mainApi?: any
}
}
const app = createApp(App)
app.use(vuetify).use(i18n).use(router).use(createPinia())
app.mount('#app')
import { createI18n } from 'vue-i18n'
import en from '@/renderer/locales/en.json'
import ko from '@/renderer/locales/ko.json'
import zh from '@/renderer/locales/zh.json'
import zhHant from '@/renderer/locales/zh-hant.json'
import de from '@/renderer/locales/de.json'
import es from '@/renderer/locales/es.json'
import ja from '@/renderer/locales/ja.json'
import fr from '@/renderer/locales/fr.json'
import ru from '@/renderer/locales/ru.json'
import pt from '@/renderer/locales/pt.json'
import { getCurrentLocale } from '@/renderer/utils'
export default createI18n({
legacy: false,
locale: getCurrentLocale(),
fallbackLocale: 'en',
globalInjection: true,
messages: {
en,
ko,
zh,
zhHant,
de,
es,
ja,
fr,
ru,
pt
}
})
import { createVuetify } from 'vuetify'
import { ko, en, zhHans, zhHant, de, es, ja, fr, ru, pt } from 'vuetify/locale'
import { aliases, mdi } from 'vuetify/iconsets/mdi'
import 'vuetify/styles'
import '@mdi/font/css/materialdesignicons.min.css'
import colors from 'vuetify/lib/util/colors.mjs'
export default createVuetify({
locale: {
messages: { ko, en, zhHans, zhHant, de, es, ja, fr, ru, pt },
locale: 'en',
fallback: 'en'
},
icons: {
defaultSet: 'mdi',
aliases,
sets: {
mdi
}
},
theme: {
themes: {
light: {
dark: false,
colors: {
primary: colors.green.darken2
}
},
dark: {
dark: true,
colors: {
primary: colors.green.darken4
}
}
}
}
})
import { MainScreen, ErrorScreen, SecondScreen } from '@/renderer/screens'
import { createRouter, createWebHashHistory } from 'vue-router'
export default createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
component: MainScreen,
meta: {
titleKey: 'title.main'
}
},
{
path: '/second',
component: SecondScreen,
meta: {
titleKey: 'title.second'
}
},
{
path: '/error',
component: ErrorScreen,
meta: {
titleKey: 'title.error'
}
},
{
path: '/:pathMatch(.*)*',
redirect: '/'
}
]
})
<template>
<div>Unknown error occurred</div>
</template>
<script setup lang="tsx">
import { useI18n } from 'vue-i18n'
import { useTheme } from 'vuetify'
import { openExternal } from '@/renderer/utils'
import { useCounterStore } from '@/renderer/store/counter'
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'
const { locale, availableLocales } = useI18n()
const { counterIncrease } = useCounterStore()
const { counter } = storeToRefs(useCounterStore())
const theme = useTheme()
const languages = ref(['en'])
const appVersion = ref('Unknown')
onMounted((): void => {
languages.value = availableLocales
// Get application version from package.json version string (Using IPC communication)
window.mainApi.receive('msgReceivedVersion', (event: Event, version: string) => {
appVersion.value = version
})
window.mainApi.send('msgRequestGetVersion')
})
const handleChangeTheme = (): void => {
theme.global.name.value = theme.global.current.value.dark ? 'light' : 'dark'
}
const handleChangeLanguage = (val): void => {
locale.value = val
}
const handleOpenDocument = async (): Promise<void> => {
await openExternal('https://vutron.jooy2.com')
}
const handleOpenGitHub = async (): Promise<void> => {
await openExternal('https://github.com/jooy2/vutron')
}
const handleCountIncrease = (): void => {
counterIncrease(1)
}
</script>
<template>
<v-container>
<v-row no-gutters align="center" class="text-center">
<v-col cols="12" md="7">
<h2 class="my-4">Hello Electron</h2>
<p>{{ $t('desc.welcome-desc') }}</p>
<p class="my-4">
App Version: <strong>{{ appVersion }}</strong>
</p>
<v-row class="my-4">
<v-col cols="3">
<v-btn icon color="primary" @click="handleChangeTheme">
<v-icon icon="mdi-brightness-6" />
<v-tooltip activator="parent" location="bottom">
{{ $t('menu.change-theme') }}
</v-tooltip>
</v-btn>
</v-col>
<v-col cols="3">
<v-badge data-testid="counter-badge" color="blue" :content="counter">
<v-btn data-testid="btn-counter" icon color="primary" @click="handleCountIncrease">
<v-icon icon="mdi-plus-circle" />
<v-tooltip activator="parent" location="bottom">
{{ $t('menu.increase-count') }}
</v-tooltip>
</v-btn>
</v-badge>
</v-col>
<v-col cols="3">
<v-btn icon color="primary" @click="handleOpenDocument">
<v-icon icon="mdi-file-document" />
<v-tooltip activator="parent" location="bottom">
{{ $t('menu.documentation') }}
</v-tooltip>
</v-btn>
</v-col>
<v-col cols="3">
<v-btn icon color="primary" @click="handleOpenGitHub">
<v-icon icon="mdi-github" />
<v-tooltip activator="parent" location="bottom">
{{ $t('menu.github') }}
</v-tooltip>
</v-btn>
</v-col>
<v-col cols="12">
<v-select
data-testid="select-language"
:model-value="locale"
density="compact"
:label="$t('menu.change-language')"
:items="languages"
@update:model-value="handleChangeLanguage"
>
{{ $t('menu.change-language') }}
</v-select>
</v-col>
</v-row>
</v-col>
</v-row>
</v-container>
</template>
<template>
<v-container>
<v-row no-gutters align="center" class="text-center">
<v-col cols="12">
<v-icon icon="mdi-emoticon-cool-outline" size="250" color="#009f57" />
</v-col>
<v-col cols="12" class="my-4">{{ $t('desc.second-desc') }}</v-col>
</v-row>
</v-container>
</template>
import ErrorScreen from '@/renderer/screens/ErrorScreen.vue'
import MainScreen from '@/renderer/screens/MainScreen.vue'
import SecondScreen from '@/renderer/screens/SecondScreen.vue'
export { ErrorScreen, MainScreen, SecondScreen }
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
counter: 0
}),
getters: {
getCounter: (state): number => state.counter
},
actions: {
counterIncrease(amount: number) {
this.counter += amount
}
}
})
export default class Utils {
static getCurrentLocale(): string {
return navigator?.language?.split('-')[0] || 'en'
}
static async openExternal(url: string): Promise<void> {
await window.mainApi.send('msgOpenExternalLink', url)
}
}
export const { getCurrentLocale, openExternal } = Utils
declare module '*.vue' {
import { defineComponent } from 'vue'
const component: ReturnType<typeof defineComponent>
export default component
}
import { Page, _electron as electron } from 'playwright'
import { ElectronApplication } from 'playwright-core'
import { test, expect } from '@playwright/test'
let appWindow: Page
let appElectron: ElectronApplication
function existElementByTestId(selector: string, waitingMilliseconds = 100) {
return new Promise((resolve) => {
setTimeout(async () => {
await expect(
appWindow.getByTestId(selector).first(),
`Confirm selector '${selector}' is visible`
).toBeVisible()
resolve(true)
}, waitingMilliseconds)
})
}
test.beforeAll(async () => {
// Open Electron app from build directory
appElectron = await electron.launch({ args: ['dist/main/index.js'] })
appWindow = await appElectron.firstWindow()
await appWindow.waitForEvent('load')
})
test('Environment check', async () => {
const isPackaged = await appElectron.evaluate(async ({ app }) => {
return app.isPackaged
})
expect(isPackaged, 'Confirm that is in development mode').toBe(false)
})
test('Document element check', async () => {
await existElementByTestId('main-logo')
await existElementByTestId('select-language')
})
test('Counter button click check', async () => {
await appWindow.getByTestId('btn-counter').click({ clickCount: 10, delay: 50 })
const counterValueElement = await appWindow
.getByTestId('counter-badge')
.getByRole('status')
.innerHTML()
expect(counterValueElement).toBe('10')
})
test.afterAll(async () => {
await appWindow.waitForTimeout(2000)
await appElectron.close()
})
{
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist",
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"jsx": "preserve",
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"declaration": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"sourceMap": true,
"strict": true,
"skipLibCheck": true,
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"]
},
"include": ["src/*.ts", "src/*.d.ts", "src/renderer"],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"jsx": "preserve",
"moduleResolution": "node",
"composite": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/main", "src/preload", "package.json", "vite.config.ts", "buildAssets/builder"]
}
import { fileURLToPath } from 'url'
import { defineConfig } from 'vite'
import ElectronPlugin from 'vite-plugin-electron'
import RendererPlugin from 'vite-plugin-electron-renderer'
import EslintPlugin from 'vite-plugin-eslint'
import VuetifyPlugin from 'vite-plugin-vuetify'
import VueJsx from '@vitejs/plugin-vue-jsx'
import Vue from '@vitejs/plugin-vue'
import { rmSync } from 'fs'
import { resolve, dirname } from 'path'
import { builtinModules } from 'module'
export default defineConfig(() => {
rmSync('dist', { recursive: true, force: true })
return {
define: {
__VUE_I18N_FULL_INSTALL__: true,
__VUE_I18N_LEGACY_API__: false,
__INTLIFY_PROD_DEVTOOLS__: false
},
resolve: {
extensions: ['.mjs', '.js', '.ts', '.vue', '.json', '.scss'],
alias: {
'@': resolve(dirname(fileURLToPath(import.meta.url)), 'src')
}
},
base: './',
root: resolve('./src/renderer'),
publicDir: resolve('./src/renderer/public'),
clearScreen: false,
build: {
assetsDir: '', // See: https://github.com/electron-vite/electron-vite-vue/issues/287
outDir: resolve('./dist')
},
plugins: [
Vue(),
VueJsx(),
// Docs: https://github.com/vuetifyjs/vuetify-loader
VuetifyPlugin({
autoImport: true
}),
// Docs: https://github.com/gxmari007/vite-plugin-eslint
EslintPlugin(),
// Docs: https://github.com/electron-vite/vite-plugin-electron
ElectronPlugin([
{
entry: ['src/main/index.ts', 'src/main/index.dev.ts'],
onstart: (options) => {
options.startup()
},
vite: {
build: {
assetsDir: '.',
outDir: 'dist/main',
rollupOptions: {
external: ['electron', ...builtinModules]
}
}
}
},
{
entry: ['src/preload/index.ts'],
onstart: (options) => {
options.reload()
},
vite: {
build: {
outDir: 'dist/preload'
}
}
}
]),
RendererPlugin()
]
}
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment