【问题标题】:How to run electron on a localhost server in Build as well as in Dev如何在构建和开发中的本地主机服务器上运行电子
【发布时间】:2021-08-19 07:11:31
【问题描述】:

我正在使用Next.js + Electron + Typescript 进行开发。 我正在使用npx create-next-app --example with-electron-typescript 命令生成代码。

npm run dev(内容为npm run build-electron && electron .),貌似本地服务器已经在localhost8000上运行起来了,但是在构建的时候,服务器内部并没有运行起来,直接访问文件就运行了。

但是,如果 location.origin 中没有域,则某些 API 无法正常工作,因此它在 Dev 中有效,但在 Build 中无效。

所以,如果可能的话,我想在构建版本和开发版本中在 localhost 上运行服务器。 有什么办法可以让它发挥作用吗?

【问题讨论】:

  • 您能否向我们展示您在何处/如何触发这些请求,并告诉我们您在谈论哪些 API?
  • 我正在尝试使用 Skyway.js 要使用此服务,需要允许特定域。 webrtc.ecl.ntt.com/en/documents/…

标签: node.js typescript electron next.js


【解决方案1】:

在任何示例中都没有显示,即使有人要求提供: https://github.com/vercel/next.js/issues/28225

可以使用自定义服务器: https://nextjs.org/docs/advanced-features/custom-server

您可以按照以下步骤创建一个:

  1. 克隆 Electron Next TypeScript 示例存储库: https://github.com/vercel/next.js/tree/canary/examples/with-electron-typescript

  2. 使用以下代码更新./electron-src/index.ts

import isDev from 'electron-is-dev';
import { createServer } from 'http';
import next from 'next';
import { parse } from 'url';

app.on('ready', async () => {

  // Use server-side rendering for both dev and production builds
  const nextApp = next({
    dev: isDev,
    dir: app.getAppPath() + '/renderer'
  });
  const requestHandler = nextApp.getRequestHandler();

  // Build the renderer code and watch the files
  await nextApp.prepare();

  // Create a new native HTTP server (which supports hot code reloading)
  createServer((req: any, res: any) => {
    const parsedUrl = parse(req.url, true)
    requestHandler(req, res, parsedUrl)
  }).listen(3000, () => {
    console.log('> Ready on http://localhost:3000')
  })

  mainWindow.loadURL('http://localhost:3000/')
  1. 更新 ./package.json Electron 构建配置以包含渲染器 src 文件:
  "build": {
    "asar": true,
    "files": [
      "main",
      "renderer"
    ]
  }
  1. ./package.json 中将nextdevDependencies 移动到dependencies。这意味着它可以在生产版本中运行

然后使用有用的脚本来解压二进制文件并查看里面的文件/文件夹:

npx asar extract ./dist/mac/ElectronTypescriptNext.app/Contents/Resources/app.asar ./dist/unpack

运行解压后的版本进行调试:

./node_modules/.bin/electron ./dist/unpack

我已经创建了 Express Server 版本和 NextJS 版本来证明这是可能的: https://github.com/kmturley/electron-server/tree/feature/express https://github.com/kmturley/electron-server/tree/feature/next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多