Electron與TypeScript的結合
Electron與TypeScript的結合
概述
本文檔簡要地說明使用Electron與TypeScript構建一個簡單的桌面應用程序。
項目結構
my-electron-app/
├── dist/ // TypeScript 編譯后的輸出目錄
├── src/ // 源代碼目錄
│ ├── main.ts // 主進程代碼
│ ├── preload.ts // 預加載腳本
│ └── renderer.ts // 渲染進程代碼
├── index.html // 渲染進程的 HTML 文件
├── package.json // 項目配置文件
├── tsconfig.json // TypeScript配置文件
我們先根據上述項目結構,創建空白文件:
配置
package.json定義項目的入口文件和腳本:
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "a simple electron demo",
"main": "./dist/main.js",
"author": "bing",
"license": "MIT",
"scripts": {
"build": "tsc",
"start": "npm run build && electron ./dist/main.js"
}
}
- 安裝依賴
# 設置環境臨時變量
set ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
# 安裝Electron依賴
yarn add electron --dev
安裝完成:
package.json 文件新增一項:
tsconfig.json配置TypeScript編譯選項:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
launch.json配置 VS Code 調試環境:
{
"version": "0.2.0",
"compounds": [
{
"name": "Main + renderer",
"configurations": ["Main", "Renderer"],
"stopAll": true
}
],
"configurations": [
{
"name": "Renderer",
"port": 9222,
"request": "attach",
"type": "chrome",
"webRoot": "${workspaceFolder}"
},
{
"name": "Main",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": [".", "--remote-debugging-port=9222"],
"outputCapture": "std",
"console": "integratedTerminal"
}
]
}
配置前:
配置后:
請將運行和調試選項切換到 “Main+Render”:
代碼實現
main.ts主進程負責管理應用程序的生命周期和窗口:
import { app, BrowserWindow, ipcMain } from "electron";
import path from "path";
let mainWindow: BrowserWindow | null;
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"), // Preload script
},
});
// Load the HTML file for the renderer process
mainWindow.loadFile(path.join(__dirname, "../index.html"));
mainWindow.on("closed", () => {
mainWindow = null;
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (mainWindow === null) {
createWindow();
}
});
// Listen for messages from the renderer process
ipcMain.handle("get-app-info", () => {
return {
appName: app.getName(),
appVersion: app.getVersion(),
};
});
preload.ts預加載腳本用于在主進程和渲染進程之間安全地傳遞數據:
import { contextBridge, ipcRenderer } from 'electron';
// Expose a safe API to the renderer process
contextBridge.exposeInMainWorld('electronAPI', {
getAppInfo: (): Promise<{ appName: string; appVersion: string }> => ipcRenderer.invoke('get-app-info'),
});
renderer.ts渲染進程負責處理用戶界面邏輯:
// Define the ElectronAPI interface
interface ElectronAPI {
getAppInfo: () => Promise<{ appName: string; appVersion: string }>;
}
// Retrieve electronAPI from the preload script
const electronAPI: ElectronAPI = (
window as unknown as { electronAPI: ElectronAPI }
).electronAPI;
// Fetch application information and display it on the page
electronAPI.getAppInfo().then((info) => {
const appInfoElement = document.getElementById("app-info");
if (appInfoElement) {
appInfoElement.innerText = `App: ${info.appName}, Version: ${info.appVersion}`;
}
});
index.html渲染進程的 HTML 文件定義了用戶界面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self';"
/>
<title>Electron + TypeScript Demo</title>
</head>
<body>
<h1>Hello, Electron!</h1>
<div id="app-info">Loading app info...</div>
<script src="./dist/renderer.js"></script>
</body>
</html>
現在,我們已填充除 dist目錄下 外所有的文件:
運行項目
- 編譯 TypeScript 代碼:
npm run build
- 啟動 Electron 應用:
npm start
效果:
聲明
內容準確性: 我會盡力確保所分享信息的準確性和可靠性,但由于個人知識有限,難免會有疏漏或錯誤。如果您在閱讀過程中發現任何問題,請不吝賜教,我將及時更正。
AI: 文章部分代碼參考了DeepSeek和ChatGTP大語言模型生成的內容。
posted on 2025-03-05 17:55 wubing7755 閱讀(251) 評論(0) 收藏 舉報
浙公網安備 33010602011771號