vite+vue3.0+ts+electron

用vue-cli+electron 完成了一个小项目,最近尝试用vite+vue3+ts+electron搭建了框架 以及一些使用时碰到的坑

一、搭建项目

第一步、建立vite新项目

yarn create vite

安装项目依赖

yarn add -D concurrently cross-env electron electron-builder wait-on
//安装的时候可能会报错 Response code 404 (Not Found) for //https://npm.taobao.org/mirrors/electron/v16.0.7/electron-v16.0.7-win32-x64.zip
//这是因为找不到16.0.7这个版本,改为:
yarn add -D concurrently cross-env [email protected] electron-builder wait-on//就能解决


 

修改package.json文件

添加build节点

  "build":{
  "appId":"项目ID(com.***.** 建议:不要使用中文命名)",
  "productName":"App名称",
  "directories":{
   "output":"build" /*打包文件的名称*/
 },
 "electronDownload":{
  "mirror":"https://npm.taobao.org/mirrors/electron/"
},
"publish":[
    {
     "provider":"********",
     "url":"https://*****************(服务端放latest.yml和***Setup 4.19.0.exe的地址)" 
    }
 ],
"nsis":{
 "oneClick":false,
 "allowToChangeInstallationDirectory":true
},
"files":[
"dist/**/*",
"electron/**/*"
],
"directories":{
   "buildResources":"assets",
   "output":"dist_electron"
}
}

修改scripts节点

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

添加main节点

"main":"electron/electron.js"

 编辑vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
// https://vitejs.dev/config/
export default defineConfig({
  base:  './',
  plugins: [vue()]
})

在项目根文件创建新文件夹electron并创建electron.js(electron主进程文件)

  const path = require('path')
  const { app,BrowserWindow}=require('electron');
  const isDev = process.env.IS_DEV == "true" ? true : false; //判断环境 true为开发环境 false为线上环境
  function createWindow() {
  // Create the browser window.
   const mainWindow = new BrowserWindow({
   width: 800,
   height: 600,
   webPreferences: {
   preload: path.join(__dirname, 'preload.js'),
   nodeIntegration: true,
   },
 });
  // and load the index.html of the app.
  // win.loadFile("index.html");
  mainWindow.loadURL(
  isDev
   ? 'http://localhost:3000'
  : `file://${path.join(__dirname, '../dist/index.html')}`
  );
   // Open the DevTools.
   if (isDev) {
    mainWindow.webContents.openDevTools();
  }
  }
  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
   // On macOS it's common to re-create a window in the app when the
   // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  });
  // Quit when all windows are closed, except on macOS. There, it's common
  // for applications and their menu bar to stay active until the user quits
  // explicitly with Cmd + Q.
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
   app.quit();
  }
  });

 再创建预加载文件preload.js

// electron/preload.js
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
 window.addEventListener('DOMContentLoaded', () => {
     const replaceText = (selector, text) => {
       const element = document.getElementById(selector)
       if (element) element.innerText = text
     }
  
     for (const dependency of ['chrome', 'node', 'electron']) {
       replaceText(`${dependency}-version`, process.versions[dependency])
     }
 })
*****************************************************************************************
//本人没整明白上面的代码是干啥用的  以下是我对preload.js的用法
const {contextBridge,ipcRenderer} = require('electron')
contextBridge.exposeInMainWorld('electron',{
  send:(name)=>{
    if(name=="cancel"){
      ipcRenderer.send("window_close"); 
    }else if(name=="minMax"){
      ipcRenderer.send("window-min")
    }
  }  
})

在.vue文件里
                    
                    

你可能感兴趣的:(electron,vue.js,typescript)