Giter Site home page Giter Site logo

caoxiemeihao / electron-vite-samples Goto Github PK

View Code? Open in Web Editor NEW
121.0 1.0 15.0 16.96 MB

Electron⚡️Vite samples, includes C/C++ addons | 样板代码集合,包含 C/C++ 扩展

License: MIT License

TypeScript 73.73% HTML 5.39% CSS 6.93% JavaScript 12.82% Svelte 1.13%
vite boilerplate electron template node-native-addons better-sqlite3 serialport sqlite3

electron-vite-samples's Introduction

electron-vite-samples

此仓库为 electron-vite 组织的最佳实践方案合集。

This repository is a collection of best practices orgzized by electron-vite.

🍵 🍰 🍣 🍟

这个项目如果能帮到你解决工作中的问题,还希望你能请V我50,或者直接点击 Sponsor 支持我!😘

If this repository helps you, I hope you can click Sponsor to donate me. ❤️

electron-vite-samples's People

Contributors

amazingrise avatar caoxiemeihao 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

electron-vite-samples's Issues

serialport-renderer-process 项目什么都没改,dev正常,build打包报错

serialport-renderer-process 项目什么都没改,dev正常,build打包报错:

node:internal/modules/cjs/loader:1084 Uncaught Error: Cannot find module '@serialport/parser-byte-length'
Require stack:

  • D:\HK\Obj\Electron\serialport-renderer-process\release\0.0.0\win-unpacked\resources\app\node_modules\serialport\dist\index.js
  • D:\HK\Obj\Electron\serialport-renderer-process\release\0.0.0\win-unpacked\resources\app\dist\index.html
    at node:internal/modules/cjs/loader:1084:15
    at Function._resolveFilename (node:electron/js2c/renderer_init:2:3225)
    at node:internal/modules/cjs/loader:929:27
    at Function. (node:electron/js2c/asar_bundle:2:13327)
    at Function._load (node:electron/js2c/renderer_init:2:2455)
    at Module.require (node:internal/modules/cjs/loader:1150:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object. (D:\HK\Obj\Electron\s…dist\index.js:17:14)
    at Object. (D:\HK\Obj\Electron\s…\dist\index.js:30:3)
    at Module._compile (node:internal/modules/cjs/loader:1271:14)

Class extends value undefined is not a constructor or null

你好,我按照教程配置了serialport,但是提示类继承了空的,看源码好像是require导入的stream模块识别不到

image
image

// vite.config.ts
import { defineConfig } from "vite";
import path from "node:path";
import electron from "vite-plugin-electron/simple";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    electron({
      main: {
        // Shortcut of `build.lib.entry`.
        entry: "electron/main.ts",
        vite: {
          build: {
            minify: false,
            rollupOptions: {
              external: ['serialport'],
            },
          },
        },
      },
      preload: {
        // Shortcut of `build.rollupOptions.input`.
        // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.
        input: path.join(__dirname, "electron/preload.ts"),
      },
    }),
  ],
});
<script setup lang="ts">
import { onMounted } from 'vue';
import { SerialPort } from 'serialport'

onMounted(async () => {
  await SerialPort.list();
})
</script>

<template>
  <div>App.vue</div>
</template>

<style scoped>

</style>

__dirname is not defined

import "./index.css";
import { ipcRenderer } from "electron";
console.log(
  '👋 This message is being logged by "renderer.ts", included via Vite'
);
ipcRenderer.send("ping");

报错:
image

windows 下使用better-sqlite3例子遇到了 "__require.resolve is not a function" 的问题记录

问题描述

控制台报错 __require.resolve is not a function vite启动失败。
对应的源码:

const better_sqlite3 = require.resolve('better-sqlite3')

问题原因

具体原因不清楚。
个人猜测:require 是cjs中的语法,目前框架只能用esm,所以报错了。

解决方案

如果package.json中有"type": "module",删掉即可

npm install 失败,node-gyp rebuild 没有日志输出,不好排查原因

这是我修改过后的rebuild.js,因为install最后报错,但是看日志并没有具体执行过程的输出,找不到问题,因为我对nodejs并不熟悉,我网上找了办法去显示子线程的日志,然后才找到rebuild失败的原因;

const path = require('path');
const child = require('child_process');


function execute(cmd, callback, cwd = process.cwd()) {
  return new Promise((resolve, reject) => {
    let items = cmd
    let exe = items.shift()
    let processor = child.spawn(exe, items, { cwd })
    let collect = () => {
      let str = ''
      let print = () => {
        let lines = str.split(/[\n|\r\n]/)
        str = lines.pop()
        let contents = lines.join('\r\n')
        if (str === '') { // 如果本来内容就是完整断句的,这里进行修正,表示结尾是正常断句的
          contents += '\r\n'
        }
        callback(contents)
      }
      return (data) => {
        str += data.toString()
        print()
      }
    }
    if (typeof callback === 'function') {
      processor.stdout.on('data', collect())
      processor.stderr.on('data', collect())
    }
    processor.on('exit', code => {
      if (code === 0) {
        console.log('Rebuild better-sqlite3 success.');
      }
      process.exit(code);
    });
    processor.on('error', reject)
    processor.on('close', resolve)
  })
}

// If you prefer electron-rebuild:
// 👉 https://github.com/WiseLibs/better-sqlite3/blob/v8.5.2/docs/troubleshooting.md#electron
// 👉 https://stackoverflow.com/questions/46384591/node-was-compiled-against-a-different-node-js-version-using-node-module-versio/52796884#52796884

const better_sqlite3 = require.resolve('better-sqlite3');
const better_sqlite3_root = path.posix.join(better_sqlite3.slice(0, better_sqlite3.lastIndexOf('node_modules')), 'node_modules/better-sqlite3');
// const cp = child.spawn(
//   process.platform === 'win32' ? 'npm.cmd' : 'npm',
//   [
//     'run',
//     'build-release',
//     `--target=${process.versions.electron}`,
//     // https://github.com/electron/electron/blob/v26.1.0/docs/tutorial/using-native-node-modules.md#manually-building-for-electron
//     '--disturl=https://electronjs.org/headers',
//   ],
//   {
//     cwd: better_sqlite3_root,
//     stdio: 'inherit',
//   },
// );


// cp.on('exit', code => {
//   if (code === 0) {
//     console.log('Rebuild better-sqlite3 success.');
//   }
//   process.exit(code);
// });

const cmd = [
  'win32' ? 'npm.cmd' : 'npm',
  'run',
  'build-release',
  `--target=${process.versions.electron}`,
  // https://github.com/electron/electron/blob/v26.1.0/docs/tutorial/using-native-node-modules.md#manually-building-for-electron
  '--distUrl=https://electronjs.org/headers',
]

execute(cmd, (contents) => console.log(contents), better_sqlite3_root).catch(e => console.log(e))

顺便给其他新手说下我出现的问题和解决方法:

  1. 需要安装Visual studio (工作负荷勾选安装 使用c++的桌面开发),Python
  2. .npmrc 添加 electron-mirror=https://npmmirror.com/mirrors/electron/
    msvs_version=2022 //根据你自己的安装版本和路径来
    msbuild_path=F:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe
  3. node-gyp是npm内置了的,不需要再去npm install -g node-gyp, 项目里使用的node-gyp不会使用你自己全局安装的;npm需要更新为最新,因为之前用的node-gyp v8.4.1不行,报错: fatal error C1189: #error: "It looks like you are building this native module without using the right config.gypi. This normally means that you need to update electron-rebuild (>=3.2.8) or node-gyp (>=9.0.0) if you're building modules directly." ; 只能更新为最新的npm才能成功执行;

windows下better-sqlite3-main-process报错 ENOENT: no such file or directory

image
我使用的Windows电脑,在better-sqlite3-main-process/下运行示例时,会报ENOENT错误
查询发现是vite.config.ts文件中自定义插件vite-plugin-binding-sqlite3中的路径有一些问题。
vite导出的normalizePath方法处理window下绝对路径后,再通过path.posix.xxx方法处理仍然不兼容。

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.