node.js - 如何在构建和开发中的本地主机服务器上运行电子
问题描述
我正在与Next.js + Electron + Typescript
. 我正在使用该npx create-next-app --example with-electron-typescript
命令生成代码。
npm run dev
(内容为npm run build-electron && electron .
),貌似本地服务器在localhost8000上已经启动并运行,但是在构建的时候,服务器内部并没有启动,直接访问文件是运行的。
但是,如果 中没有域,则某些 API 无法正常工作location.origin
,因此它在 Dev 中有效,但在 Build 中无效。
因此,如果可能的话,我想在构建版本和开发版本中的 localhost 上运行服务器。我能做些什么让它发挥作用吗?
解决方案
它没有显示在任何示例中,即使有人要求提供: https ://github.com/vercel/next.js/issues/28225
可以使用自定义服务器: https ://nextjs.org/docs/advanced-features/custom-server
您可以按照以下步骤创建一个:
克隆 Electron Next TypeScript 示例仓库: https ://github.com/vercel/next.js/tree/canary/examples/with-electron-typescript
./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/')
- 更新
./package.json
Electron 构建配置以包含渲染器 src 文件:
"build": {
"asar": true,
"files": [
"main",
"renderer"
]
}
- 在
./package.json
从到。next
_ 这意味着它将可以在生产版本中运行devDependencies
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 /功能/下一个