Electron结合Vue使用说明
创始人
2024-03-23 18:02:46

Electron结合Vue使用说明

1. 创建Vue项目:

npm init vue

2. 创建Electron项目

npm init electron-app@latest electron-project --template=webpack-typescript

npm install copy-webpack-plugin --save-dev

3. 项目配置

1.配置Vue项目:

1)配置base路径

// vite.config.ts
export default defineConfig({plugins: [vue(), vueJsx()],resolve: {alias: {"@": fileURLToPath(new URL("./src", import.meta.url)),},},base: "./", // 新增配置(解决绝对路径导致HTML请求文件失败的问题)
});

2)配置路由为哈希路由

// router/index.ts
import { createRouter, createWebHashHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";const router = createRouter({history: createWebHashHistory(import.meta.env.BASE_URL), // 修改为Hash模式routes: [{path: "/",name: "home",component: HomeView,},{path: "/about",name: "about",component: () => import("../views/AboutView.vue"),},],
});export default router;
2.配置Electron项目

1)修改入口文件,将开发环境与Vue结合

// src/index.ts
// 用于Vue开发环境
if(process.env.npm_lifecycle_event === 'start'){mainWindow.loadURL(<前端项目地址,如('http://localhost:5174')>);
} else {mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
}

2)修改webpack配置,将Vue打包文件整合至Electron打包环境

// webpack.renderer.config.ts
export const rendererConfig: Configuration = {module: {rules},plugins: [// 新增,在打包是将Vue项目整合至Electronnew CopyPlugin({patterns: [{// 将dist目录文件(排除index.html)拷贝至.webpack/renderer/main_windowfrom: "./dist/**",to: ({ context, absoluteFilename }) => {const relativePath = path.relative(context, absoluteFilename).replace(/^dist/, ".");const basePath = path.resolve(__dirname,".webpack/renderer/main_window");return path.resolve(basePath, relativePath);},globOptions: {ignore: ["**/dist/index.html"],},},],}),...plugins,],resolve: {extensions: [".js", ".ts", ".jsx", ".tsx", ".css"],},
};

3)修改forge入口

const config: ForgeConfig = {
packagerConfig: {},rebuildConfig: {},makers: [new MakerSquirrel({}),new MakerZIP({}, ["darwin"]),new MakerRpm({}),new MakerDeb({}),],plugins: [new WebpackPlugin({mainConfig,renderer: {config: rendererConfig,entryPoints: [{html: "./dist/index.html", // 将HTML文件入口指向Vue打包文件js: "./src/renderer.ts",name: "main_window",preload: {js: "./src/preload.ts",},},],},}),],
};

4. 开发

1.运行Vue项目
2.运行Electron项目

5. 打包

1.将Vue打包后的 dist 目录复制到Electron工程根目录
2.打包Electron

相关内容

热门资讯

十字对开门冰箱热卖排行榜 小户... 清晨阳光斜照进整洁的厨房,一碗隔夜炖好的银耳羹仍清润如初,青菜叶片挺括水灵,鸡蛋壳上还凝着细微水珠—...
最新冰箱性价比推荐 学生宿舍低... 清晨赶早课前顺手取一杯冰镇酸奶,深夜复习时打开冰箱拿一盒水果补充能量——对学生党而言,一台安静、省电...
再走长征路|心栖娄山:一个“候... 中经记者 王登海 黄永旭 遵义报道仲夏时节,黔北大地暑气渐盛,来自四川的退休教师赵俊毅提前20多天来...
铸魂聚力 实干兴业 (来源:沈阳日报)转自:沈阳日报  7月10日,全国五一劳动奖章获得者苏广林在中国工商银行沈阳南站支...
摩根大通AI投资组合回测跑赢传...   摩根大通最新发布的研究报告显示,其开发的八个人工智能投资代理在长达二十年的历史回测中,表现超越了...