Vue3 + Vite + Electron + TS 项目构建

效果图

1. 创建项目

运行命令,选择 vue + ts

bash 复制代码
pnpm create vite

2. 安装依赖

2.1 electron

bash 复制代码
pnpm add electron -D

2.2 electron-builder

打包工具

bash 复制代码
pnpm add electron-builder -D

2.3 electron-devtools-installer

开发工具

bash 复制代码
pnpm add electron-devtools-installer -D

2.4 vite-plugin-electron、vite-plugin-electron-renderer

集成 Vite 和 Electron,方便后续在渲染进程中使用 Node API 或 Electron API

bash 复制代码
pnpm add vite-plugin-electron -D
bash 复制代码
pnpm add vite-plugin-electron-renderer -D

2.5 rimraf

快速删除文件和文件夹

bash 复制代码
pnpm add rimraf -D

3. 创建 electron 窗口

根目录创建 electron 文件夹,创建 index.ts、preload.ts

3.1 编辑 index.ts

javascript 复制代码
// electron-main/index.ts

import { app, BrowserWindow } from "electron";

import path from "path";



const createWindow = () => {

  const win = new BrowserWindow({

    webPreferences: {

      contextIsolation: false, // 是否开启隔离上下文

      nodeIntegration: true, // 渲染进程使用Node API

      preload: path.join(__dirname, "./preload.js"), // 需要引用js文件

    },

  });



  // 如果打包了,渲染index.html

  if (process.env.NODE_ENV !== "development") {

    win.loadFile(path.join(__dirname, "./index.html"));

    win.webContents.openDevTools();

  } else {

    let url = "http://localhost:5173"; // 本地启动的vue项目路径。注意:vite版本3以上使用的端口5173;版本2用的是3000

    win.loadURL(url);

    win.webContents.openDevTools();

  }

};



app.whenReady().then(() => {

  createWindow(); // 创建窗口

  app.on("activate", () => {

    if (BrowserWindow.getAllWindows().length === 0) createWindow();

  });

});



// 关闭窗口

app.on("window-all-closed", () => {

  if (process.platform !== "darwin") {

    app.quit();

  }

});

3.2 编辑 preload.ts

javascript 复制代码
// electron-preload/preload.ts

import os from "os";

console.log("platform", os.platform());

4. 编辑 tsconfig.app.json

将 electron 文件下的 ts 文件添加到编译

javascript 复制代码
{

  "compilerOptions": {

    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",

    "target": "ES2020",

    "useDefineForClassFields": true,

    "module": "ESNext",

    "lib": ["ES2020", "DOM", "DOM.Iterable"],

    "skipLibCheck": true,



    /* Bundler mode */

    "moduleResolution": "Bundler",

    "allowImportingTsExtensions": true,

    "isolatedModules": true,

    "moduleDetection": "force",

    "noEmit": true,

    "jsx": "preserve",



    /* Linting */

    "strict": true,

    "noUnusedLocals": true,

    "noUnusedParameters": true,

    "noFallthroughCasesInSwitch": true,

    "noUncheckedSideEffectImports": true

  },

  "include": [

    "src/**/*.ts",

    "src/**/*.tsx",

    "src/**/*.vue",

    "electron/**/**.ts"

  ]

}

5. 编辑 vite.config.ts

javascript 复制代码
import { defineConfig } from "vite";

import vue from "@vitejs/plugin-vue";



import electron from "vite-plugin-electron";

import electronRenderer from "vite-plugin-electron-renderer";



export default defineConfig(({ mode }) => ({

  base: mode == "development" ? "" : "./",

  plugins: [

    vue(),

    electron([

      {

        entry: "electron/index.ts", // 主进程文件

      },

      {

        entry: "electron/preload.ts",

      },

    ]),

    electronRenderer(),

  ],

  build: {

    emptyOutDir: false, // 默认情况下,若 outDir 在 root 目录下,则 Vite 会在构建时清空该目录

    outDir: "dist-electron",

  },

}));

6. 编辑 package.json

javascript 复制代码
{

  "name": "electron-vue3-ts-vite",

  "private": true,

  "version": "0.0.0",

  "main": "dist-electron/index.js",

  "scripts": {

    "dev": "vite",

    "build": "vue-tsc -b && rimraf dist-electron && vite build && electron-builder",

    "preview": "vite preview"

  },

  "dependencies": {

    "vue": "^3.2.47"

  },

  "devDependencies": {

    "@vitejs/plugin-vue": "^4.1.0",

    "electron": "^25.2.0",

    "electron-builder": "^24.4.0",

    "electron-devtools-installer": "^3.2.0",

    "rimraf": "^5.0.1",

    "typescript": "^5.0.2",

    "vite": "^4.3.9",

    "vite-plugin-electron": "^0.12.0",

    "vite-plugin-electron-renderer": "^0.14.5",

    "vue-tsc": "^1.4.2"

  },

  "build": {

    "appId": "com.electron.desktop",

    "productName": "electron",

    "asar": true,

    "copyright": "Copyright © 2022 electron",

    "directories": {

      "output": "release/${version}"

    },

    "files": ["./dist", "./package.json", "./dist-electron"],

    "mac": {

      "artifactName": "${productName}_${version}.${ext}",

      "target": ["dmg"]

    },

    "win": {

      "target": [

        {

          "target": "nsis",

          "arch": ["x64"]

        }

      ],

      "artifactName": "${productName}_${version}.${ext}"

    },

    "nsis": {

      "oneClick": false,

      "allowElevation": true,

      "allowToChangeInstallationDirectory": true,

      "installerIcon": "public/timg.ico",

      "uninstallerIcon": "public/timg.ico",

      "installerHeader": "public/timg.ico",

      "installerHeaderIcon": "public/timg.ico",

      "installerSidebar": "public/installerSiddebar.bmp",

      "uninstallerSidebar": "public/uninstallerSiddebar.bmp",

      "uninstallDisplayName": "${productName}${version}",

      "createDesktopShortcut": true,

      "createStartMenuShortcut": true,

      "shortcutName": "TestApp",

      "include": "script/installer.nsi",

      "script": "script/installer.nsi",

      "deleteAppDataOnUninstall": false,

      "runAfterFinish": true,

      "menuCategory": false

    },

    "publish": [

      {

        "provider": "generic",

        "url": "http://127.0.0.1:8080"

      }

    ],

    "releaseInfo": {

      "releaseNotes": "版本更新的具体内容"

    }

  }

}
相关推荐
风尚云网10 分钟前
风尚云网前端学习:一个简易前端新手友好的HTML5页面布局与样式设计
前端·css·学习·html·html5·风尚云网
木子020413 分钟前
前端VUE项目启动方式
前端·javascript·vue.js
GISer_Jing15 分钟前
React核心功能详解(一)
前端·react.js·前端框架
捂月18 分钟前
Spring Boot 深度解析:快速构建高效、现代化的 Web 应用程序
前端·spring boot·后端
深度混淆25 分钟前
实用功能,觊觎(Edge)浏览器的内置截(长)图功能
前端·edge
Smartdaili China26 分钟前
如何在 Microsoft Edge 中设置代理: 快速而简单的方法
前端·爬虫·安全·microsoft·edge·社交·动态住宅代理
秦老师Q27 分钟前
「Chromeg谷歌浏览器/Edge浏览器」篡改猴Tempermongkey插件的安装与使用
前端·chrome·edge
滴水可藏海28 分钟前
Chrome离线安装包下载
前端·chrome
endingCode31 分钟前
45.坑王驾到第九期:Mac安装typescript后tsc命令无效的问题
javascript·macos·typescript
m512738 分钟前
LinuxC语言
java·服务器·前端