首页 > 解决方案 > 在 electron-forge 应用程序中使用 express 提供静态文件

问题描述

我编写了一个快速的Electron Forge应用程序,它只运行一个在本地提供静态文件的快速网络服务器。为了可用性,我更喜欢直接运行节点进程。

main.js

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

const exApp = express();
exApp.use(express.static('web-app'));
exApp.listen(3333);

let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
  // ...
  });

  // ...
};

// ...

我使用CopyWebpackPlugin将需要提供的文件复制到.webpack/main/web-app/目录中。

webpack.main.config.js

module.exports = {
  /**
   * This is the main entry point for your application, it's the first file
   * that runs in the main process.
   */
  entry: './src/main.js',
  // Put your normal webpack config below here
  module: {
    rules: require('./webpack.rules'),
  },
  plugins: [
    new CopyPlugin([
      { from: path.resolve(__dirname, 'web-app'), to: 'web-app' }
    ]),
  ]
};

这在开发中非常有效(通过yarn start)。

当我尝试运行yarn make时,它成功构建了应用程序并生成了一个可运行的 exe,但在运行应用程序后尝试访问http://localhost:3333/,会导致Cannot GET /404 消息。

知道我做错了什么吗?

标签: node.jsexpresselectronelectron-forge

解决方案


我在开发中服务的实际上是web-app与节点进程相关的目录,而不是复制到.webpack/....

为了在生产中提供正确的文件,我将exApp.use()行更改为:

exApp.use(express.static('resources/app/.webpack/main/web-app'));

推荐阅读