electron project first article vite +vue3 build electron project

vite + vue3 build electron project

        • 1 Use vite to create a vue3 project
        • 2 Install electron dependencies
        • 3 Embedding electron
          • 3.1 Create electron directory
          • 3.2 Configure electron plugin
          • 3.3 Writing electron main process
          • 3.4 Configure electron startup entry
          • 3.5 Start the project, minor bug fixes
            • 3.5.1 Console error solution
            • 3.5.2 Modify the project icon
            • 3.5.3 Solve the problem of configuring process.env.PUBLIC ts error
            • 3.5.4 Modify the isolatedModules property
        • 4 Packaging electron
          • 4.1 Installation depends on electron-builder
          • 4.2 Modify package.json file configuration
          • 4.3 Execute packaging

1 Use vite to create a vue3 project

  1. Open powershell on the desktop, enter the command npm create vite@latest (enter the project name, select vue, typescript), and then open the project with vscode, the directory is as follows

2 Install electron dependencies

  1. Install the electron plugin in the project
// electron plugin
npm install electron -D

// vite build electron application
npm install vite-plugin-electron -D

// The electron plugin can be used in the project built by vite, and it needs to be used in the communication of later projects
npm install vite-plugin-electron-renderer -D

3 embed electron

3.1 Create electron directory

Create an electron directory under the root directory, create a main directory (main process) and a preload directory (rendering process) under the electron directory.

3.2 Configure electron plugin

In vite.config.ts, configure the Electron entry file, refer to configuration

// vite.config.ts
import {<!-- --> defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import electron from 'vite-plugin-electron'
import renderer from 'vite-plugin-electron-renderer'

// https://vitejs.dev/config/
export default defineConfig({<!-- -->
  plugins: [
    vue(),
    electron([
      // Main process configuration
      {<!-- -->
        // package entry
        entry: 'electron/main/index.ts',
        onstart(options) {<!-- -->
          // start electron project
          options. startup()
        },
        vite: {<!-- -->
          build: {<!-- -->
            // build export
            outDir: 'dist-electron/main',
          },
        },
      },
      // Rendering process configuration
      {<!-- -->
        entry: 'electron/preload/index.ts',
        onstart(options) {<!-- -->
          // Load the renderer process configuration
          options. reload()
        },
        vite: {<!-- -->
          build: {<!-- -->
            outDir: 'dist-electron/preload',
          },
        },
      }
    ]),
    renderer({<!-- -->
      // The rendering process is integrated into node
      nodeIntegration: true,
    })
  ],
})

3.3 Writing electron main process
// electron/main/index.ts
import {<!-- --> app, BrowserWindow } from "electron";
import {<!-- --> join } from "path";

// Configure the output file directory path when building
process.env.DIST_ELECTRON = join(__dirname, "..");
// Configure the output file directory path after packaging
process.env.DIST = join(process.env.DIST_ELECTRON, "../dist");
// Configure the public file directory path, VITE_DEV_SERVER_URL indicates the service url generated by vite by default
process.env.PUBLIC = process.env.VITE_DEV_SERVER_URL
  ?join(process.env.DIST_ELECTRON, "../public")
  : process.env.DIST;

// Configure the packaged file loading path
const indexHtml = join(process.env.DIST, "index.html");
// This requires electron to load the compiled js file
const preload = join(__dirname, "../preload/index.js");
// service path when vite starts the project
const url = process.env.VITE_DEV_SERVER_URL;

let mainWind: BrowserWindow | null = null;
function createWind() {<!-- -->
    mainWind = new BrowserWindow({<!-- -->
        webPreferences: {<!-- -->
            preload,
            // The rendering process can call methods in node
            nodeIntegration: true,
            contextIsolation: false,
        },
    });

    if (url) {<!-- -->
        // Load the local development path
        mainWind.loadURL(url);

        // Development and debugging
        mainWind.webContents.openDevTools();
        mainWind. maximize();
    } else {<!-- -->
        // load path after packaging
        mainWind.loadFile(indexHtml);
    }
}

app.whenReady().then(() => {<!-- -->
    createWind();
    app.on('activate', () => {<!-- -->
        // This solves the problem that after the mac system closes the app, but there is still an icon in the dock, click again to recreate the process
        if(BrowserWindow. getAllWindows. length === 0) createWind();
    })
})

app.on('window-all-closed', () => {<!-- -->
    // electron runs in three environments (win32 Windows system, linux Linux system, darwin Mac system)
    // The solution here is for non-mac systems, the program exits the process (the app will remain in the dock when the Mac system is closed)
    if(process. platform !== 'darwin') app. quit();
})

3.4 Configure electron startup entry

Delete “type”: “module” in the package.json file (configured as a module will not be able to use the es module mode), configure the main file entry

{<!-- -->
  "name": "markdown-electron",
  "description": "markdown electron project",
  "main": "dist-electron/main/index.js",
  "private": true,
  "version": "0.0.0",
  "author": "dan",
  "license": "MIT",
  "keywords": [
    "electron",
    "rollup",
    "vite",
    "vue3",
    "vue"
  ],
  "scripts": {<!-- -->
    "dev": "vite",
    "build": "vue-tsc & amp; & amp; vite build",
    "preview": "vite preview"
  },
  "dependencies": {<!-- -->
    "vue": "^3.2.47"
  },
  "devDependencies": {<!-- -->
    "@vitejs/plugin-vue": "^4.1.0",
    "electron": "^23.2.0",
    "typescript": "^4.9.3",
    "vite": "^4.2.0",
    "vite-plugin-electron": "^0.11.1",
    "vite-plugin-electron-renderer": "^0.13.6",
    "vue-tsc": "^1.2.0"
  }
}

3.5 Start project, minor bug fixes

Run the command npm run dev

3.5.1 Console error solution

Add the following code in the root directory index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg + xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- Solve the console warning problem -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
    <title>MARKDOWN</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
3.5.2 Modify project icon

Add a favicon.ico icon in the public directory (find your favorite icon on the Internet by yourself), and then modify the electron entry file

function createWind() {<!-- -->
  mainWind = new BrowserWindow({<!-- -->
  // Add icon, path identification mentioned earlier in process.env.PUBLIC
    icon: join(process.env.PUBLIC, "favicon.ico"),
    webPreferences: {<!-- -->
      nodeIntegration: true,
      contextIsolation: false,
      preload,
    },
  });
}
3.5.3 Solve the problem of configuring process.env.PUBLIC ts error


The default process.env does not have the PUBLIC attribute, so the electron-env.d.ts file needs to be configured. Create a new electron-env.d.ts file in the electron directory

/// <reference types="vite-plugin-electron/electron-env" />

declare namespace NodeJS {<!-- -->
  interface ProcessEnv {<!-- -->
    DIST_ELECTRON: string
    DIST: string
    PUBLIC: string
  }
}

After adding the above files, you need to modify the tsconfig.json file

// tsconfig.json
"include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "electron/**/*.ts", //Add .ts recognition under electron
    "electron/**/*.d.ts", //Add .d.ts recognition under electron
  ],
3.5.4 Modify the isolatedModules attribute

By default, isolatedModules is enabled, so an error will be reported in the ts file

Need to modify the isolatedModules property under tsconfig.json

// tsconfig.json
"isolatedModules": false, // default is true

4 package electron

4.1 Installation depends on electron-builder
npm install electron-builder -D
4.2 Modify package.json file configuration
// package.json
{<!-- -->
  "name": "markdown-electron",
  "description": "markdown electron project",
  "main": "dist-electron/main/index.js",
  "private": true,
  "version": "0.0.1",
  "author": "dan",
  "license": "MIT",
  "keywords": [
    "electron",
    "rollup",
    "vite",
    "vue3",
    "vue"
  ],
  "scripts": {<!-- -->
    "dev": "vite",
    "build": "vue-tsc --noEmit & amp; & amp; vite build & amp; & amp; electron-builder",
    "preview": "vite preview"
  },
  // package configuration
  "build": {<!-- -->
    "appId": "Markdown",
    "asar": true,
    "icon": "public/favicon.ico",
    "directories": {<!-- -->
      "output": "release/${version}"
    },
    "files": [
      "dist-electron",
      "dist"
    ],
    "mac": {<!-- -->
      "artifactName": "${productName}_${version}.${ext}",
      "target": [
        "dmg"
      ]
    },
    "win": {<!-- -->
      "target": [
        {<!-- -->
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ],
      "artifactName": "${productName}_${version}.${ext}"
    },
    "nsis": {<!-- -->
      "oneClick": false,
      "perMachine": false,
      "allowToChangeInstallationDirectory": true,
      "deleteAppDataOnUninstall": false
    }
  },
  "dependencies": {<!-- -->
    "vue": "^3.2.47"
  },
  "devDependencies": {<!-- -->
    "@vitejs/plugin-vue": "^4.1.0",
    "electron": "^23.2.0",
    "electron-builder": "^23.6.0",
    "typescript": "^4.9.3",
    "vite": "^4.2.0",
    "vite-plugin-electron": "^0.11.1",
    "vite-plugin-electron-renderer": "^0.13.6",
    "vue-tsc": "^1.2.0"
  }
}

electron-builder configuration reference

4.3 Executing packaging
npm run build

At this point, project construction and packaging are perfect. source address