You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建整合Angular+TypeScript的Electron桌面应用及本地文件访问

整合Electron与Angular(TypeScript)及本地文件系统访问指南

一、项目整合步骤(TypeScript版本)

1. 在现有Angular项目中添加Electron依赖

进入Angular项目根目录,执行以下命令安装依赖:

npm install electron electron-builder --save-dev
npm install @types/electron --save-dev
npm install concurrently wait-on ts-node --save-dev

2. 配置Electron主进程与预加载脚本

在项目根目录创建electron文件夹,新建main.ts(主进程文件):

import { app, BrowserWindow, ipcMain } from 'electron';
import * as path from 'path';
import * as fs from 'fs';

let mainWindow: BrowserWindow | null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.ts')
    }
  });

  // 开发/生产环境加载逻辑区分
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:4200');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/[你的Angular项目名]/index.html'));
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

在electron文件夹内新建preload.ts(安全桥接脚本):

import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('electronAPI', {
  getFileSystemInfo: () => ipcRenderer.invoke('get-file-system-info')
});

3. 配置TypeScript编译规则

在项目根目录新建tsconfig-electron.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./dist-electron",
    "target": "ES2020",
    "module": "CommonJS",
    "esModuleInterop": true
  },
  "include": ["electron/**/*"]
}

4. 修改package.json配置

  • 添加主入口字段:"main": "dist-electron/main.js"
  • 更新scripts命令:
"scripts": {
  "electron:dev": "concurrently \"ng serve\" \"wait-on http://localhost:4200 && NODE_ENV=development ts-node -P tsconfig-electron.json electron/main.ts\"",
  "electron:build": "ng build --prod && tsc -P tsconfig-electron.json && electron-builder"
}

5. 启动开发环境

执行npm run electron:dev,Angular服务启动后,Electron窗口会自动加载页面并打开开发者工具。

二、本地文件系统访问实现

1. 在主进程添加文件系统处理逻辑

修改electron/main.ts,添加IPC处理函数:

// 处理Angular的文件系统请求
ipcMain.handle('get-file-system-info', async () => {
  const docsPath = app.getPath('documents');
  const files = fs.readdirSync(docsPath);
  return {
    documentsPath: docsPath,
    fileList: files
  };
});

2. 在Angular组件中调用Electron API

在任意Angular组件中添加如下代码:

import { Component, OnInit } from '@angular/core';

declare global {
  interface Window {
    electronAPI: {
      getFileSystemInfo: () => Promise<{ documentsPath: string; fileList: string[] }>;
    };
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  docsPath: string = '';
  fileList: string[] = [];

  async ngOnInit() {
    try {
      const result = await window.electronAPI.getFileSystemInfo();
      this.docsPath = result.documentsPath;
      this.fileList = result.fileList;
    } catch (err) {
      console.error('获取文件系统信息失败:', err);
    }
  }
}

3. 模板展示数据

在组件模板中添加渲染代码:

<div class="file-system-info">
  <h3>用户文档目录:{{ docsPath }}</h3>
  <ul>
    <li *ngFor="let file of fileList">{{ file }}</li>
  </ul>
</div>

三、关键注意事项

  • 必须保持contextIsolation: true和nodeIntegration: false,这是Electron官方推荐的安全规范,所有Node.js API调用都要通过预加载脚本桥接。
  • 生产打包时,确认Angular项目名与dist目录下的文件夹名称一致,避免加载路径错误。
  • 文件系统操作需添加错误捕获逻辑,防止未授权访问或文件不存在导致应用崩溃。

内容的提问来源于stack exchange,提问作者user19551915

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:31:22