Electron结合Vue使用说明

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请求文件失败的问题)
 server: { // 新增,配置开发服务器静态端口
   port: 5237,
   strictPort: true,
 },
});

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.NODE_ENV === 'development') {
  mainWindow.loadURL('http://127.0.0.1:5237') // 配置成前端的开发服务器
} else {
  mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY)
}

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

// webpack.renderer.config.ts
import type { Configuration } from 'webpack'

import { rules } from './webpack.rules'
import { plugins } from './webpack.plugins'
// eslint-disable-next-line import/default
import CopyPlugin from 'copy-webpack-plugin'
import path from 'path'

// =========新增,在打包是将Vue项目整合至Electron=========
process.env.NODE_ENV = process.env.npm_lifecycle_event === 'start' ? 'development' : 'production'
const newPlugins: any[] = [...plugins]
if (process.env.NODE_ENV === 'production') {
  newPlugins.push(
    new CopyPlugin({
      patterns: [
        {
          // 将dist目录文件(排除index.html)拷贝至.webpack/renderer/main_window
          from: './dist/**',
          to: ({ context, absoluteFilename }: { context: string; absoluteFilename: string }) => {
            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'],
          },
        },
      ],
    })
  )
}
// ==================================================

rules.push({
  test: /\.css$/,
  use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
})

export const rendererConfig: Configuration = {
  module: {
    rules,
  },
  plugins: newPlugins, // 修改
  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)Prettier 代码格式化配置(可选)

npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev
// .eslintrc.json
{
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:import/recommended",
    "plugin:import/electron",
    "plugin:import/typescript",
    "plugin:prettier/recommended", // 新增prettier插件
    "prettier" // 新增prettier设置
  ],
  "parser": "@typescript-eslint/parser"
}
// .prettierrc.json (可根据需求自行修改代码格式样式,个人配置如下)
{
  "semi": false,
  "singleQuote": true,
  "printWidth": 120,
  "tailingComma": "none",
  "arrowParens": "avoid"
}

4. 开发

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

5. 打包

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

你可能感兴趣的:(Eelectron结合Vue,vue.js,electron,javascript)