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

如何在Electron中渲染打包后的简易Web应用?

解决Electron加载打包后HTML/JS出现404和MIME类型错误的问题

你的问题核心是路径匹配错误:Electron加载时找不到bundle.js,服务器返回404后把错误页面(HTML)当成脚本返回,导致MIME类型不匹配。以下是具体修复步骤:

1. 修正HTML中bundle.js的引入路径

打开dist-app/index.html,检查脚本引入的路径:

  • 如果原来写的是绝对路径(比如<script src="/bundle.js"></script>),改为相对路径:
    <script src="./bundle.js"></script>
    
    确保路径相对于index.html所在的dist-app文件夹,这样本地file协议或dev server都能正确找到文件。

2. 调整Electron窗口的加载方式

Electron-forge的webpack-typescript模板默认会启动dev server(http://localhost:3000),但你的dist-app是本地静态文件,dev server默认不会从这个目录提供资源,导致404。有两种修复方式:

方式一:让dev server指向dist-app目录

修改forge.config.ts中的Webpack插件配置,指定dev server的静态文件目录:

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

const config: ForgeConfig = {
  // ...其他配置
  plugins: [
    new WebpackPlugin({
      mainConfig: './webpack.main.config.ts',
      renderer: {
        config: './webpack.renderer.config.ts',
        entryPoints: [
          {
            html: './dist-app/index.html',
            // 移除原有的js入口,因为你已经用自己打包的bundle.js
          },
        ],
        // 配置dev server从dist-app加载静态资源
        devServer: {
          static: './dist-app',
        },
      },
    }),
  ],
};

export default config;

方式二:直接加载本地file协议的HTML

跳过dev server,直接加载本地静态文件,适合不需要热重载的场景:
修改主进程代码(src/main.ts):

import { app, BrowserWindow } from 'electron';
import path from 'path';

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // 加载本地index.html,注意路径要匹配你的项目结构
  mainWindow.loadFile(path.join(__dirname, '../dist-app/index.html'));

  // 打开开发者工具(可选)
  // mainWindow.webContents.openDevTools();
}

app.whenReady().then(() => {
  createWindow();
  // ...其他窗口生命周期代码
});

3. 确保生产打包时包含dist-app文件夹

如果要打包成生产应用,需要让Electron-forge把dist-app文件夹打包进去:
在forge.config.ts中添加packagerConfig:

const config: ForgeConfig = {
  // ...其他配置
  packagerConfig: {
    // 把dist-app作为额外资源打包到应用中
    extraResource: ['./dist-app'],
  },
};

同时修改主进程中的路径判断,适配生产环境:

const isDev = process.env.NODE_ENV === 'development';
let htmlPath: string;

if (isDev) {
  htmlPath = path.join(__dirname, '../dist-app/index.html');
} else {
  // 生产打包后,extraResource会放在应用的resources目录下
  htmlPath = path.join(process.resourcesPath, 'dist-app/index.html');
}

mainWindow.loadFile(htmlPath);

验证修复

  • 重启Electron应用,检查控制台是否还有404错误
  • 确认页面能正常渲染,bundle.js加载成功

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:56:34