Giter Site home page Giter Site logo

cawa-93 / vite-electron-builder Goto Github PK

View Code? Open in Web Editor NEW
2.2K 26.0 243.0 5.62 MB

Secure boilerplate for Electron app based on Vite. TypeScript + Vue/React/Angular/Svelte/Vanilla

License: MIT License

TypeScript 81.45% Vue 13.34% HTML 1.51% JavaScript 3.70%
vue typescript vite electron electron-builder template vite-electron best-practices boilerplate vue-tsc

vite-electron-builder's Introduction

Important

This project is mainrained by developer from Ukraine πŸ‡ΊπŸ‡¦

Due to the ongoing war resulting from Russia's full-scale invasion of Ukraine, I currently lack the time for the full development of this open-source project. My primary focus is on ensuring the well-being of myself and my family. I'll prioritize and review all new contributions as soon as possible.

If you can, please consider supporting Ukraine or me personally.

Thank you for your understanding and support.


Vite Electron Builder Boilerplate

This is a template for secure electron applications. Written following the latest safety requirements, recommendations and best practices.

Under the hood is Vite β€” A next-generation blazing fast bundler, and electron-builder for packaging.

Get started

Follow these steps to get started with the template:

  1. Click the Use this template button (you must be logged in) or just clone this repo.
  2. If you want to use another package manager you may need to edit .github/workflows since npm is used as default. (See also #944)

    Note: This template configured to install peerDependencies automatically.

That's all you need. πŸ˜‰

❀️ If you like this template, don't forget to give a ⭐ or send support!

Features

Electron Electron version

  • This template uses the latest electron version with all the latest security patches.
  • The architecture of the application is built according to the security guides and best practices.
  • The latest version of the electron-builder is used to package the application.

Vite Vite version

  • Vite is used to bundle all source codes. It's an extremely fast bundler, that has a vast array of amazing features. You can learn more about how it is arranged in this video.
  • Vite supports reading .env files. You can also specify the types of your environment variables in types/env.d.ts.
  • Automatic hot-reloads for the Main and Renderer processes.

Vite provides many useful features, such as: TypeScript, TSX/JSX, CSS/JSON Importing, CSS Modules , Web Assembly and much more.

See all Vite features.

TypeScript TypeScript version (optional)

  • The latest version of TypeScript is used for all the source code.
  • Vite supports TypeScript out of the box. However, it does not support type checking.
  • Code formatting rules follow the latest TypeScript recommendations and best practices thanks to @typescript-eslint/eslint-plugin.

Guide to disable typescript and remove dependencies

Vue Vue version (optional)

  • By default, web pages are built using Vue. However, you can easily change that. Or not use additional frameworks at all.
  • Code formatting rules follow the latest Vue recommendations and best practices thanks to eslint-plugin-vue.

Find more forks πŸ”± for others frameworks or setups

Continuous Integration

  • The configured workflow will check the types for each push and PR.
  • The configured workflow will check the code style for each push and PR.
  • Automatic tests used Vitest Vitest version -- A blazing fast test framework powered by Vite.
    • Unit tests are placed within each package and are ran separately.
    • End-to-end tests are placed in the root tests directory and use playwright.

Workflow graph

Publishing

  • Each time you push changes to the main branch, the release workflow starts, which creates a new draft release. For each next commit will be created and replaced artifacts. That way you will always have draft with latest artifacts, and the release can be published once it is ready.
    • Code signing supported. See release workflow.
    • Auto-update is supported. After the release is published, all client applications will download the new version and install updates silently.

Note: This template configured only for GitHub public repository, but electron-builder also supports other update distribution servers. Find more in electron-builder docs.

How it works

The template requires a minimum amount dependencies. Only Vite is used for building, nothing more.

Project Structure

The structure of this template is very similar to a monorepo. The entire source code of the project is divided into three modules (packages) that are each bundled independently:

  • packages/renderer. Responsible for the contents of the application window. In fact, it is a regular web application. In developer mode, you can even open it in a browser. The development and build process is the same as for classic web applications. Access to low-level API electrons or Node.js is done through the preload layer.
  • packages/preload. Contain Electron preload scripts. Acts as an intermediate bridge between the renderer process and the API exposed by electron and Node.js. Runs in an isolated browser context, but has direct access to the full Node.js functionality.
  • packages/main Contain Electron main script. This is the main process that powers the application. It manages creating and handling the spawned BrowserWindow, setting and enforcing secure permissions and request handlers. You can also configure it to do much more as per your need, such as: logging, reporting statistics and health status among others.

Schematically, the structure of the application and the method of communication between packages can be depicted as follows:

flowchart TB;

packages/preload <-. IPC Messages .-> packages/main

    subgraph packages/main["packages/main (Shared beatween all windows)"]
    M[index.ts] --> EM[Electron Main Process Modules]
    M --> N2[Node.js API]
    end

subgraph Window["Browser Window"]
    subgraph packages/preload["packages/preload (Works in isolated context)"]
    P[index.ts] --> N[Node.js API]
    P --> ED[External dependencies]
    P --> ER[Electron Renderer Process Modules]
    end


    subgraph packages/renderer
    R[index.html] --> W[Web API]
    R --> BD[Bundled dependencies]
    R --> F[Web Frameworks]
    end
    end

packages/renderer -- Call Exposed API --> P

Build web resources

The main and preload packages are built in library mode as it is simple javascript. The renderer package builds as a regular web app.

Compile App

The next step is to package a ready to distribute Electron app for macOS, Windows and Linux with "auto update" support out of the box.

To do this, use electron-builder:

  • Using the npm script compile: This script is configured to compile the application as quickly as possible. It is not ready for distribution, it is compiled only for the current platform and is used for debugging.
  • Using GitHub Actions: The application is compiled for any platform and ready-to-distribute files are automatically added as a draft to the GitHub releases page.

Working with dependencies

Because the renderer works and builds like a regular web application, you can only use dependencies that support the browser or compile to a browser-friendly format.

This means that in the renderer you are free to use any frontend dependencies such as Vue, React, lodash, axios and so on. However, you CANNOT use any native Node.js APIs, such as, systeminformation. These APIs are only available in a Node.js runtime environment and will cause your application to crash if used in the renderer layer. Instead, if you need access to Node.js runtime APIs in your frontend, export a function form the preload package.

All dependencies that require Node.js api can be used in the preload script.

Expose in main world

Here is an example. Let's say you need to read some data from the file system or database in the renderer.

In the preload context, create a function that reads and returns data. To make the function announced in the preload available in the render, you usually need to call the electron.contextBridge.exposeInMainWorld. However, this template uses the unplugin-auto-expose plugin, so you just need to export the method from the preload. The exposeInMainWorld will be called automatically.

// preload/index.ts
import { readFile } from 'node:fs/promises';

// Encapsulate types if you use typescript
interface UserData {
  prop: string
}

// Encapsulate all node.js api
// Everything you exported from preload/index.ts may be called in renderer
export function getUserData(): Promise<UserData> {
  return readFile('/path/to/file/in/user/filesystem.json', {encoding:'utf8'}).then(JSON.parse);
}

Now you can import and call the method in renderer

// renderer/anywere/component.ts
import { getUserData } from '#preload'
const userData = await getUserData()

Find more in Context Isolation tutorial.

Working with Electron API

Although the preload has access to all of Node.js's API, it still runs in the BrowserWindow context, so a limited electron modules are available in it. Check the electron docs for full list of available methods.

All other electron methods can be invoked in the main.

As a result, the architecture of interaction between all modules is as follows:

sequenceDiagram
renderer->>+preload: Read data from file system
preload->>-renderer: Data
renderer->>preload: Maximize window
activate preload
preload-->>main: Invoke IPC command
activate main
main-->>preload: IPC response
deactivate main
preload->>renderer: Window maximized
deactivate preload

Find more in Inter-Process Communication tutorial.

Modes and Environment Variables

All environment variables are set as part of the import.meta, so you can access them vie the following way: import.meta.env.

Note: If you are using TypeScript and want to get code completion you must add all the environment variables to the ImportMetaEnv in types/env.d.ts.

The mode option is used to specify the value of import.meta.env.MODE and the corresponding environment variables files that need to be loaded.

By default, there are two modes:

  • production is used by default
  • development is used by npm run watch script

When running the build script, the environment variables are loaded from the following files in your project root:

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified env mode
.env.[mode].local   # only loaded in specified env mode, ignored by git

Warning: To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.

For example let's take the following .env file:

DB_PASSWORD=foobar
VITE_SOME_KEY=123

Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY to your client source code, but DB_PASSWORD will not.

You can change that prefix or add another. See envPrefix

Contribution

See Contributing Guide.

vite-electron-builder's People

Contributors

boydbloemsma avatar caoxiemeihao avatar cawa-93 avatar danilopolani avatar dependabot[bot] avatar dharmaturtle avatar dohooo avatar elimisteve avatar fractal-tess avatar github-actions[bot] avatar hieblmedia avatar maximilize avatar raphaelmenges avatar renovate-bot avatar renovate[bot] avatar s00d avatar sabertazimi avatar tanimodori avatar udondan avatar vovchisko avatar xiaohulu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-electron-builder's Issues

Renderer process can not import electron

I add below code to renderer/app.vue

import {ipcRenderer} from 'electron';

then npm run watch report errors index.js:4 Uncaught ReferenceError: __dirname is not defined
npm run compile success, but load failed and report errors index.html:1 Uncaught TypeError: Failed to resolve module specifier "electron". Relative references must start with either "/", "./", or "../".

npm run watch can not work

When I execute npm run watch command, the window opened, but throw below errors

图片

vite version is 2.0.1.

Make the template IDE independent

Is your feature request related to a problem? Please describe.
Currently the template has IntelliJ IDEA settings built in. I think it would be more convenient for people not to have it in the template, especially if they use a different editor.

Describe the solution you'd like

  1. Remove /.idea
  2. Add .idea and .vscode to .gitignore

I can make a PR with this if the author agrees

the command line has error related to libva

the command line has error related to libva, but vite-electron-builder seems work still,

Describe the bug

 2021-05-17 16:21:28 ⌚  ming-manjaro in ~/learn/js/vite-electron-builder
Β± |main U:1 βœ—| β†’ npm run watch

> watch
> node scripts/watch.js

δΈ‹εˆ4:21:36 [main] libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name = (null)

δΈ‹εˆ4:21:36 [main] Failed install extension: Error: Version of Electron: 12.0.7 does not match required range >=1.2.1 for extension ljjemllljcmogpfapbkkighbhhppjdbg
    at install (/home/ming/learn/js/vite-electron-builder/packages/main/dist/index.js:7873:29)
    at /home/ming/learn/js/vite-electron-builder/packages/main/dist/index.cjs:52:100

To Reproduce
Steps to reproduce the behavior:

  1. git clone
  2. npm run watch

Expected behavior
no errors

Additional context
my env:

Lib versions
node: v14.16.0
v8: v8.9.255.25-electron.0
uv: v1.40.0
zlib: v1.2.11
brotli: v1.0.9
ares: v1.16.1
modules: v87
nghttp2: v1.41.0
napi: v7
llhttp: v2.1.3
openssl: v1.1.1
icu: v68.1
unicode: v13.0
electron: v12.0.7
chrome: v89.0.4389.128
 2021-05-17 16:26:00 ⌚  ming-manjaro in ~/learn/js/vite-electron-builder
Β± |main U:1 βœ—| β†’ node -v
v14.17.0

 2021-05-17 16:26:10 ⌚  ming-manjaro in ~/learn/js/vite-electron-builder
Β± |main U:1 βœ—| β†’ npm -v
7.13.0

 2021-05-17 16:26:18 ⌚  ming-manjaro in ~/learn/js/vite-electron-builder
Β± |main U:1 βœ—| β†’ screenfetch 

 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     ming@ming-manjaro
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     OS: Manjaro 21.0.3 Ornara
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Kernel: x86_64 Linux 5.9.16-1-MANJARO
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Uptime: 9h 13m
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ            β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Packages: 1228
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Shell: bash
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Resolution: 1920x1080
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     DE: KDE 5.81.0 / Plasma 5.21.4
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     WM: KWin
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     GTK Theme: Breath [GTK2/3]
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Icon Theme: breath2
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     Disk: 92G / 114G (85%)
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     CPU: AMD Ryzen 7 PRO 4750U with Radeon Graphics @ 12x 1.697GHz
 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ     GPU: SVGA3D; build
                                  RAM: 7640408064-

 2021-05-17 16:26:23 ⌚  ming-manjaro in ~/learn/js/vite-electron-builder

Vite error: "vue.js.map is outside of Vite serving allow list" if project path contains spaces

Describe the bug

Getting the error shown below on launch.
I found the cause - it happens if the project path contains spaces. Not sure how to resolve the issue though. I guess Vite cannot resolve non-encoded URLs containing characters like %20

Error:

[vite] Internal server error: The request url "E:/vite%20electron/vite-electron-builder/node_modules/.vite/vue.js.map" is outside of Vite serving allow list:

- /E:/vite electron/vite-electron-builder

Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.
      at ensureServingAccess (E:\vite electron\vite-electron-builder\node_modules\vite\dist\node\chunks\dep-24231913.js:64798:15)
      at viteServeRawFsMiddleware (E:\vite electron\vite-electron-builder\node_modules\vite\dist\node\chunks\dep-24231913.js:64765:13)
      at call (E:\vite electron\vite-electron-builder\node_modules\vite\dist\node\chunks\dep-24231913.js:53749:7)
      at next (E:\vite electron\vite-electron-builder\node_modules\vite\dist\node\chunks\dep-24231913.js:53693:5)
      at viteTransformMiddleware (E:\vite electron\vite-electron-builder\node_modules\vite\dist\node\chunks\dep-24231913.js:65004:28)
      at processTicksAndRejections (internal/process/task_queues.js:95:5)

To Reproduce

Clone repo to path containing spaces:

  1. git clone https://github.com/cawa-93/vite-electron-builder.git
  2. cd "vite-electron-builder"
  3. npm install
  4. npm run watch

Sharing code between main and renderer processes

Is your feature request related to a problem? Please describe.
This repository is posited as an alternative to electron-webpack as the library is now in "maintenance mode" as stated in readme.

In electron-webpack, is it possible to share resources between main and renderer processes. This allows for best practices such as avoiding the hard-coding of event name strings for IPC communication via constants. In this case, common code resources are located in a folder which is a sibling to main and renderer folders.

Describe the solution you'd like
This repo should include configuration that enables sharing of code between main and renderer builds.

Describe alternatives you've considered
I've attempted to use the solution posited in this issue but this causes typescript errors. Aliases present DX issues because one can't use regular import statements like in webpack and must resort to some kind of module resolver which is beyond the scope of someone who wants to get started on an electron project quickly and easily.

Another solution I've attempted: move index.html file directly inside packages folder, setting the PACKAGE_ROOT to be packages folder. For renderer, main, and preload folders, in vite config files, change build.lib.entry value to be "[folderName]/src/index.ts" and change index.html script src to be "./renderer/src/index.tsx". This does not fix the issue and the watch tasks errors out:

Error: Cannot find module '../../common/constants'
Require stack:
- /home/user/code/polyhedral-net-factory/packages/main/dist/index.cjs
- /home/user/code/polyhedral-net-factory/node_modules/electron/dist/resources/default_app.asar/main.js

Main process code is bundled for browser environment

Describe the bug

npm run watch failed with window is undefined after add @koa/router, caused by any-promise package.

Vite seems only designed to bundle code for browser, so it uses browser field of package.json, and i found no way to disable this behavior.

To Reproduce

issue-repro-2021-05-20.zip

Steps to reproduce the behavior:

  1. npm install koa @koa/router @types/koa @types/koa__router
  2. use koa router
  3. npm run watch
  4. See error

Expected behavior

any-promise register-shim.js should not included in bundle because it has been marked for browser only.

Screenshots
If applicable, add screenshots to help explain your problem.

PS D:\~\src\github.com\cawa-93\vite-electron-builder> npm run watch

> watch
> node scripts/watch.js

δΈ‹εˆ9:48:44 [main] App threw an error during load

δΈ‹εˆ9:48:44 [main] ReferenceError: window is not defined
    at Object.<anonymous> (D:\~\src\github.com\cawa-93\vite-electron-builder\packages\main\dist\index.js:14474:27)
    at Module._compile (internal/modules/cjs/loader.js:1078:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1108:10)
    at Module.load (internal/modules/cjs/loader.js:935:32)
    at Module._load (internal/modules/cjs/loader.js:776:14)
    at Function.f._load (electron/js2c/asar_bundle.js:5:12684)
    at Module.require (internal/modules/cjs/loader.js:959:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (D:\~\src\github.com\cawa-93\vite-electron-builder\packages\main\dist\index.cjs:2:1)
    at Module._compile (internal/modules/cjs/loader.js:1078:30)

图片

Additional context

I searched about bundle for node with vite/rollup, but not found anything useful,
maybe we should use esbuild for main/preload code directly?

Can't read property 'Glob' of undefind

Describe the bug
clone the framework and yarn install,the app runs successfully,but there is a error

To Reproduce
Steps to reproduce the behavior:

  1. clone
  2. yarn install

Expected behavior
No any problem

Screenshots
image

Preload API crashes renderer

Describe the bug
When I add env object to preload API, it crashes the renderer window:

packages\preload\src\index.ts

const api: ElectronApi = {
  env: process.env,
  versions: process.versions,
}

packages\preload\types\electron-api.d.ts

interface ElectronApi {
  readonly versions: Readonly<NodeJS.ProcessVersions>;
  readonly env: Readonly<NodeJS.ProcessEnv>;
}

I'm new to Typescript. Am I doing something wrong?

If I serialize the object, it works:

const api: ElectronApi = {
  env: JSON.stringify(process.env),
  versions: process.versions,
}

But then I'd have to parse it in the renderer and declare env as a string type, which doesn't make sense.
What can be causing the problem?

To Reproduce
Steps to reproduce the behavior:

  1. Clone vite-electron-builder and add the code above to specified files
  2. npm run watch

Error resource 404 with ttf and woff files only in develop but in production all work good

Steps for reproduce problem

git clone this
npm install
npm i element-plus

modify file in /src/renderer/index.ts

import { createApp } from 'vue';
import ElementPlus from 'element-plus';
import locale from 'element-plus/lib/locale/lang/es';
import App from './App.vue';
import router from '/@/router';
import 'dayjs/locale/es';

const app = createApp(App);
app.use(ElementPlus, { size: 'medium', locale });
app.use(router);

app.mount('#app');

add in file /src/renderer/App.vue

<i class="el-icon-edit"></i>

And finally run:

npm run watch

And ready in console.log show this error.

image

Import Menu is undefined in render script

Describe the bug
Platform(Mac os)

I tried to access the Electron Menu in the render script.I used the preload for that. so i tried to import the menu from the electron api. but it was empty when i log it with in the preload script itself.
Next i tired to enable the remoteModule in the webprefrence, and tried to access the menu in the preload from remote.when i console it it showing the menu init, but when i tried to pass that to render script and console it in the render, its still don't have the menu . I tried to console log remote in the render script but it has only minimum methods only. and Menu was not there.

Below is the image which shows when i console. the remote. from render script.

image

Below is the image that i consoled from the preload script which consist all the methods , when i tried to pass the menu only from the preload script to render script still its not working. showing menu is undefined

image

Transparency

Describe the bug
Unable to create an app with transparency

To Reproduce
Steps to reproduce the behavior:

  1. Go to this line
  2. Add this transparent: true,
  3. Run npm run watch
  4. See error

Expected behavior
The app starts normally

Screenshots
image

how can i use nodejs in render process ?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Warnings when starting watch on freshly cloned template

Describe the bug

npm run watch produces the following warnings when running after cloning this template and installing deps:

> watch
> node scripts/watch.js

14:27:18 [main] (node:68741) ExtensionLoadWarning: Warnings loading extension at /Users/uninen/Library/Application Support/vite-electron-template/extensions/ljjemllljcmogpfapbkkighbhhppjdbg:
  Unrecognized manifest key 'browser_action'.
  Unrecognized manifest key 'update_url'.
  Permission 'contextMenus' is unknown or URL pattern is malformed.
  Cannot load extension with file or directory name _metadata. Filenames starting with "_" are reserved for use by the system.

(Use `Electron --trace-warnings ...` to show where the warning was created)

To Reproduce
Steps to reproduce the behavior:

  1. Clone the project
  2. Run npm install
  3. Run npm run watch

Expected behavior

No warnings.

npm run watch (TypeError: Cannot read properties of undefined (reading 'requestSingleInstanceLock'))

image

Describe the bug
TypeError: Cannot read properties of undefined (reading 'requestSingleInstanceLock')

To Reproduce
Steps to reproduce the behavior:

  1. npm install
  2. npm run watch
    δΈ‹εˆ1:45:04 [main] /workspace/normojs/korvo-browser/packages/main/dist/index.cjs:27 const isSingleInstance = require$$1.app.requestSingleInstanceLock(); TypeError: Cannot read properties of undefined (reading 'requestSingleInstanceLock')

Release for ubuntu fails due to snapcraft is not installed

Describe the bug
First, I just want to say thank you so much for this fantastic template! I was using the Vue CLI Plugin Electron Builder, but it's not as up-to-date or as awesome as Vite, and this template made converting to Vite a breeze.

Now for the issue: the only change I made to the release.yml was as per the comment:

    #    To compile the application for different platforms, use:
    #    os: [ macos-latest, ubuntu-latest, windows-latest ]

I made that change as I'm wanting to release for all platforms, and now the release fails for ubuntu-latest. It still creates the app image perfectly, but crashes at the snap store. (I believe you can check the failed action here: https://github.com/ste163/vislit/runs/3794128439?check_suite_focus=true)

To Reproduce

  1. Change your release.yml's OS line 87 to [ macos-latest, ubuntu-latest, windows-latest ]
  2. Push to main
  3. Ubuntu should fail due snapcraft not being installed. Mac and Windows should build just fine

Expected behavior
The release should build for the snap store; however, I don't really need it. I'm good with just having the app image.

Screenshots
Error message:

Error: Command failed: npx --no-install electron-builder --linux --publish always --config electron-builder.config.js
  β€’ electron-builder  version=22.11.7 os=5.8.0-1042-azure
  β€’ loaded configuration  file=/home/runner/work/vislit/vislit/electron-builder.config.js
  β€’ description is missed in the package.json  appPackageFile=/home/runner/work/vislit/vislit/package.json
  β€’ author is missed in the package.json  appPackageFile=/home/runner/work/vislit/vislit/package.json
  β€’ packaging       platform=linux arch=x64 electron=15.1.0 appOutDir=dist/linux-unpacked
  β€’ building        target=snap arch=x64 file=dist/vislit_21.10.4-1033_amd64.snap
  β€’ building        target=AppImage arch=x64 file=dist/vislit-21.10.4-1033.AppImage
  β€’ application Linux category is set to default "Utility"  reason=linux.category is not set and cannot map from macOS docs=https://www.electron.build/configuration/linux
  β€’ application Linux category is set to default "Utility"  reason=linux.category is not set and cannot map from macOS docs=https://www.electron.build/configuration/linux
  β€’ publishing      publisher=Github (owner: ste163, project: vislit, version: 21.10.4-1033)
  β€’ uploading       file=vislit-21.10.4-1033.AppImage provider=GitHub
  β€’ overwrite published file  file=vislit-21.10.4-1033.AppImage reason=already exists on GitHub
  β€’ publishing      publisher=Snap Store
  β€’ uploading       file=vislit_21.10.4-1033_amd64.snap provider=snapStore
  β¨― snapcraft is not installed, please: sudo snap install snapcraft --classic  
  β¨― /home/runner/work/vislit/vislit/node_modules/app-builder-bin/linux/x64/app-builder exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE  failedTask=build stackTrace=Error: /home/runner/work/vislit/vislit/node_modules/app-builder-bin/linux/x64/app-builder exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE
    at ChildProcess.<anonymous> (/home/runner/work/vislit/vislit/node_modules/builder-util/src/util.ts:249:14)
    at Object.onceWrapper (node:events:510:26)
    at ChildProcess.emit (node:events:390:28)
    at maybeClose (node:internal/child_process:1064:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
/home/runner/work/_actions/samuelmeuli/action-electron-builder/v1/index.js:144
				throw err;
				^

Error: Command failed: npx --no-install electron-builder --linux --publish always --config electron-builder.config.js
    at checkExecSyncError (child_process.js:621:11)
    at execSync (child_process.js:657:15)
    at run (/home/runner/work/_actions/samuelmeuli/action-electron-builder/v1/index.js:21:27)
    at runAction (/home/runner/work/_actions/samuelmeuli/action-electron-builder/v1/index.js:132:4)
    at Object.<anonymous> (/home/runner/work/_actions/samuelmeuli/action-electron-builder/v1/index.js:150:1)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) {
  status: 1,
  signal: null,
  output: [ null, null, null ],
  pid: 2006,
  stdout: null,
  stderr: null
}

Add `npx degit` instruction

Currently github has a bug that in case I'm not logged in / generate shows 404. Can you add an alternate usage method in the readme: npx degit?

Thanks

Use pnpm instead of npm

Is your feature request related to a problem? Please describe.
pnpm makes a better use of your drive, is faster than npm and results in more predictable behaviors (you cannot use packages not listed in the dependencies because they are not located in node_modules). I have seen a lot of people in the Vue ecosystem starting to use it and since this template is Vue by default I think it makes sense to switch as well.

Describe the solution you'd like
Remove npm lockfile, generate pnpm lockfile and replace all npm instructions with pnpm counterparts (cli is largely the same though)

Additional context
Comparison between npm and pnpm version if this template.

git clone https://github.com/cawa-93/vite-electron-builder.git npm
cd npm
npm install

results in a 580.8 MB directory

git clone https://github.com/cawa-93/vite-electron-builder.git pnpm
cd pnpm
rm package-lock.json
pnpm install

results in a 424.2 kB directory

I know that the space is still used somewhere else, but since those version of required packages can be reused for other node projects the space is utilized in a much better. If you have 2 electron apps based on this template you save 580.1 MB of space (size of node_modules with npm). If you have 3 of them you save 1160.2 MB and so on.

Will make a PR if the author approves.

Multiple sourcemap sources

Describe the bug
When running in development mode the sourcemaps are multiplied, resulting errors during debug

To Reproduce
Steps to reproduce the behavior:

  1. npm run watch
  2. Click on DevTools/Sources
  3. See multiple referenced sources in the Source tree (screenshot below)
  4. Click on the "About" link
  5. In the terminal you see the following error:
    5:01:31 PM [main] [20564:0818/170131.504:ERROR:CONSOLE(1)] "Could not load content for http://localhost:3000/src/components/C:/B/packages/renderer/src/components/About.vue (HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE)", source: devtools://devtools/bundled/core/sdk/sdk.js (1)

Please note the weird concatenated link.

I'm using Windows 10 and VS Code attaching debugger to the renderer process

It is also causing problems when I try to debug the renderer process, and the breakpoints are being hit, but the lines are off.

I'm not sure whether this is a vite issue or a local config problem, I have a hunch it might be related to the way how alias resolve is working, but I might be totally wrong

Expected behavior
Have all sources appear once in a source tree

Screenshots
image

yarn install warning

➜ vite-electron-builder git:(main) yarn
yarn install v1.22.17
info No lockfile found.
[1/5] πŸ” Validating package.json...
[2/5] πŸ” Resolving packages...
[3/5] 🚚 Fetching packages...
[4/5] πŸ”— Linking dependencies...
warning " > @typescript-eslint/[email protected]" has unmet peer dependency "@typescript-eslint/parser@^5.0.0".
[5/5] πŸ”¨ Building fresh packages...
success Saved lockfile.
✨ Done in 88.12s.

Watch script ignores configuration of renderer/vite.config.js

Describe the bug
We are using the vite-electron-builder template together with react-native-web. Building works fine, but the watch script does not work as expected.

Many react-native libs do not use .jsx as file extension for JSX files, they just use .js. The metro bundler which is used by react-native is fine with this. For vite we needed to add this config to the renderer:

  esbuild: {
    loader: 'tsx',
    include: [/(src|react-native-.*)\/.*\.[tj]sx?$/],
    exclude: [],
  },

This way, also .js files get treated as .jsx. However, it seems that the watch script is ignoring the packages/renderer/vite.config.js configuration.

To Reproduce
Steps to reproduce the behavior:

  1. Create a project based on vite-electron-builder
  2. Create a JSX component with the file extension .js
  3. Add the esbuild config to packages/renderer/vite.config.js
  4. Run npm run watch
  5. See error

Compile failed

Describe the bug
When the script compile is executed, the result tell me failed.

To Reproduce
Steps to reproduce the behavior:

  1. Go to the command line
  2. Execute the script compile
  3. The pack process is terminated
  4. Says that asar usage is disabled β€” this is strongly not recommended solution=enable asar and use asarUnpack to unpack files that must be externally available

Expected behavior
The script executes successfully and the Setup package file is generated.

Screenshots
D:\repos\electronjs\vite-electron-builder-main>npm run compile

vite-electron-builder@ precompile D:\repos\electronjs\vite-electron-builder-main
cross-env MODE=production npm run build

vite-electron-builder@ build D:\repos\electronjs\vite-electron-builder-main
node scripts/build.js

packages/main/
vite v2.1.2 building for production...
transforming (148) ....\node_modules\balanced-match\index.js 'default' is imported from external module 'util' but never used
βœ“ 151 modules transformed.
dist/index.cjs 3.02kb / brotli: 1.12kb
dist/index.cjs.map 5.46kb
Bundling time: 2.639s

packages/preload/
vite v2.1.2 building for production...
βœ“ 1 modules transformed.
dist/index.cjs 0.18kb / brotli: 0.13kb
dist/index.cjs.map 1.46kb
Bundling time: 108.418ms

packages/renderer/
vite v2.1.2 building for production...
βœ“ 24 modules transformed.
dist/logo.03d6d6da.png 6.69kb
dist/index.html 0.46kb
dist/index.ff4157e8.css 0.26kb / brotli: 0.15kb
dist/About.cb2527ca.js 0.57kb / brotli: 0.32kb
dist/About.cb2527ca.js.map 1.08kb
dist/About.1ce46fba.css 0.07kb / brotli: 0.05kb
dist/index.fb3e6a07.js 2.41kb / brotli: 1.07kb
dist/index.fb3e6a07.js.map 5.67kb
dist/vendor.d30bbbfa.js 64.26kb / brotli: 22.58kb
dist/vendor.d30bbbfa.js.map 629.17kb
Bundling time: 4.559s

Total bundling time: 7.313s

vite-electron-builder@ compile D:\repos\electronjs\vite-electron-builder-main
electron-builder build --config electron-builder.config.js --dir --config.asar=false

β€’ electron-builder version=22.10.5 os=10.0.19042
β€’ loaded configuration file=D:\repos\electronjs\vite-electron-builder-main\electron-builder.config.js
β€’ description is missed in the package.json appPackageFile=D:\repos\electronjs\vite-electron-builder-main\package.json
β€’ author is missed in the package.json appPackageFile=D:\repos\electronjs\vite-electron-builder-main\package.json
β€’ writing effective config file=dist\builder-effective-config.yaml
β€’ packaging platform=win32 arch=x64 electron=12.0.1 appOutDir=dist\win-unpacked
β€’ Unpacking electron zip zipPath=undefined
β€’ asar usage is disabled β€” this is strongly not recommended solution=enable asar and use asarUnpack to unpack files that must be externally available
β€’ asar usage is disabled β€” this is strongly not recommended solution=enable asar and use asarUnpack to unpack files that must be externally available

Additional context

  • Windows 10.0.19042.870 Pro x64
  • NodeJS 14.16.0
  • Windows Terminal 1.6.10571.0

Automatically infer type of exposed api in preload

A minor tweak to not duplicate code for types:

const api: ElectronApi = {
versions: process.versions,
};

Becomes:

export const api = {
  versions: process.versions,
};

interface ElectronApi {
readonly versions: Readonly<NodeJS.ProcessVersions>
}
declare interface Window {
electron: Readonly<ElectronApi>
electronRequire?: NodeRequire
}

Becomes:

declare interface Window {
	electron: Readonly<typeof import('../src/index').api>;
	electronRequire?: NodeRequire;
}

Not sure if there are any drawbacks.

Dependency Dashboard

This issue contains a list of Renovate updates and their statuses.

This repository currently has no open or pending branches.


  • Check this box to trigger a request for Renovate to run again on this repository

Refuse to use commonjs modules in favor of esm

Benefits:

This will not provide any performance enhancement or any other technical benefits.

Goal:

unify the system of modules throughout the project, regardless of the language and runtime environment.

Blocked:

The electron is currently working very poorly with esm. In addition, there is a share of modules that can not work with esm syntax.

Related:

Bug with eslint

image
I cant configure this in IDEA =( Maybe its wrong settings in project?

It appears that the Vetur config doesn't work well with Vetur v0.35.0?

Describe the bug

First: Why I'm filing this bug here. As a new-to-Vue user, I wasn't sure what in the world was going on here. I was unfamiliar with Vetur and I had to spend some time debugging the issue. While it's arguable that this is a problem with Vetur, it's definitely a distraction from getting started with Vue-in-electron fun, and I think it would be a good idea for this project to shield new users from errors unrelated to the content of the project. I think I'd recommend commenting out that line in the vetur config. (It might even be nice for new users if there was some comment documenting what in the world the Vetur config is, and/or what they should know about it)

With a fresh clone of this repo, using the latest VS Code and the latest Vetur extension (at the time of the writing). I'm getting a TON of errors (aka "red squigglies") until I disable the experimental template interpolation.

To Reproduce
Steps to reproduce the behavior:

  1. clone the repo
  2. npm install
  3. Open in VS code with the latest Vetur installed (v0.35.0)

Expected behavior
No errors in the IDE.

Screenshots
image

Additional context

  • OS: Windows 10
  • VS Code:
    • Version: 1.62.3 (user setup)
    • Commit: ccbaa2d27e38e5afa3e5c21c1c7bef4657064247
    • Date: 2021-11-17T08:11:14.551Z
    • Electron: 13.5.2
    • Chrome: 91.0.4472.164
    • Node.js: 14.16.0
    • V8: 9.1.269.39-electron.0
    • OS: Windows_NT x64 10.0.19042
  • Vetur Extension version 0.35.0

Workaround

For now, simply commenting out 'vetur.experimental.templateInterpolationService': true and running the VS Code command Vetur: Restart VLS will resolve the issue. However, I don't get types in the template.

Refactoring of Renovate configuration

Renovation does not work properly:

  • Does not combine updates of related dependencies
  • Does not link electrons and releases
  • The car network does not work

You need to investigate the causes of these problems, fix them, and simplify configuration.

static assets

Hey i'm try to use a icon fot the system tray but the bundle is not copyng the asset, i already look on the vite config but none so far work.

Could you share some example of how use static assets for icons tray and window

Can not work with node-opcua

English is not my native language; please excuse typing errors.

Describe the bug
I am developing an opc-ua client.After install node-opcua and import it in preload.ts,the project reports an error.

To Reproduce
Steps to reproduce the behavior:

  1. git clone https://github.com/cawa-93/vite-electron-builder.git
  2. cd "vite-electron-builder"
  3. npm install
  4. npm install node-opcua
  5. edit preload/src/index.ts
    import { OPCUAClient, } from "node-opcua-client";
    console.log(OPCUAClient);
  6. npm run watch

Expected behavior
No error is reported, logs are printed normally.

Screenshots
1639041758(1)

Additional context
But When i use electron-quick-start-typescript,node-opcua works fine.
So I guess it’s a problem with code compilation.I tried for a long time, but didn't find a solution.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (:onlyNpm)

Refuse to use a dependabot in favor of an alternative

Benefits:

dependabot does not have the ability to update related dependencies in a single OL. In some cases, updating one dependency and not updating another will result in a build error.

For example, you should always remember and update the electron release dependency BEFORE updating the electron dependency to avoid a situation where the collection tries to get information about an electron version that is not already in the electron release.

Related:

Possible alternatives

how to use ffi-napi?

i don't know how to use ffi-napi in this demo,could anybody tell me if you have use this module successfully

How to use electron-store.

I tried to use https://github.com/sindresorhus/electron-store, but it reported an error.

preload/index.ts

import * as Store from 'electron-store';
const api = {
  getStore: () => new Store(),
}

some.vue

import { useElectron } from '@/use/electron';
const { getAppPath,getstore} = useElectron();

 console.log(getstore()); // Then report an error

How to use electron-store

I tried to use https://github.com/sindresorhus/electron-store, but it reported an error.

preload/index.ts

import * as Store from 'electron-store';
const api = {
  getStore: () => new Store(),
}

some.vue

import { useElectron } from '@/use/electron';
const { getAppPath,getstore} = useElectron();

 console.log(getstore()); // Then report an error

Improved automatic release notes.

To do:

  • Combine committees with the same message into one record.
  • Merge committees to update the same dependency into one record
  • Maybe it makes sense to move the algorithm for generating notes from the built-in script to separate GitHub action?

Eslint not working

Describe the bug
Eslint not working

To Reproduce
Steps to reproduce the behavior:

  1. npm install
  2. Edit packages/main/src/index.ts
  3. npm run lint

Expected behavior
Eslint will show error.

Screenshots
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.