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

如何在electron-forge+Vite+TypeScript中添加外部文件夹至安装包?

解决Electron Forge打包时包含public文件夹的问题

1. 配置Electron Forge打包资源

在项目根目录的forge.config.ts(或forge.config.js)中,修改packagerConfig,添加extraResources字段指定要打包的public文件夹:

import type { ForgeConfig } from '@electron-forge/shared-types';
import { VitePlugin } from '@electron-forge/plugin-vite';

const config: ForgeConfig = {
  packagerConfig: {
    // 保留原有配置,新增如下内容
    extraResources: [
      './public/**/*' // 匹配public下所有文件及子文件夹
    ]
  },
  plugins: [
    new VitePlugin({
      // 你的Vite配置
      build: {
        // ...
      },
      renderer: {
        // ...
      }
    })
  ],
  // 其他makers等配置
};

export default config;

执行npm run make后,public文件夹会被打包到应用包的resources目录下(Windows:安装目录\resources\public;Mac:应用包Contents/Resources/public)。

2. 若需将public放在安装目录根目录(以Windows NSIS为例)

如果希望安装后public直接出现在应用的安装根目录(而非resources子目录),需要在maker配置中添加自定义脚本:

  1. 在forge.config.ts的makers数组中,为NSIS maker添加include配置:
makers: [
  // 其他makers...
  {
    name: '@electron-forge/maker-nsis',
    config: {
      include: './installer-scripts/install.nsh'
    }
  }
]
  1. 在项目根目录创建installer-scripts/install.nsh文件,写入以下NSIS脚本:
Section "PostInstall"
  ; 将public文件夹复制到安装根目录
  SetOutPath "$INSTDIR\public"
  File /r "${BUILD_RESOURCES_DIR}\public\*"
SectionEnd

3. 主进程中访问public文件夹路径

如果主进程需要读取public下的文件,可通过以下代码获取正确路径:

import { app } from 'electron';
import * as path from 'path';

// 获取安装后的public文件夹路径
const publicDirPath = path.join(path.dirname(app.getAppPath()), 'public');

内容的提问来源于stack exchange,提问作者Sebastián Águila

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:39:50