我正在做一个项目,我需要在 Electron 中构建一个桌面应用程序。大多数功能将在 React 中构建,但有一部分我们需要集成第 3 方静态 HTML 杂志。我需要一些关于如何做到这一点的建议。我目前正在构建一个概念验证应用程序,并且基于此 https://github.com/chentsulin/electron-react-boilerplate
我如何将其添加到/static/我服务器静态 HTML 文件。我知道我可以在 express 中做到这一点,但我真的不想包含整个 express 框架只是为了提供静态文件。
我在看这个https://www.npmjs.com/package/serve-static但不知道如何将它集成到我的 React 应用程序中并将其捆绑到 Electron 应用程序中。
最佳答案
我找到了另一种不使用 express
或 serve-static
的解决方案,我们只
需要自定义 Electron 内置的 interceptFileProtocol()
来提供静态内容。
代码:(main.js)
(我使用 electron-quick-start 作为 Electron 模板)
function createWindow () {
window = new BrowserWindow({ width: 800, height: 600 })
window.loadURL(url.format({
pathname: 'index.html', /* Attention here: origin is path.join(__dirname, 'index.html') */
protocol: 'file',
slashes: true
}))
window.on('closed', () => {
window = null
})
}
app.on('ready', () => {
protocol.interceptFileProtocol('file', (request, callback) => {
const url = request.url.substr(7) /* all urls start with 'file://' */
callback({ path: path.normalize(`${__dirname}/${url}`)})
}, (err) => {
if (err) console.error('Failed to register protocol')
})
createWindow()
})
引用: protocol.interceptFileProtocol()
解释:
通常,如果您将 React 应用程序作为普通网站运行,所有静态内容都应通过
HTTP [GET]
方法提供。尽管它们使用相对路径,但您的 HTTP 服务器将处理路径解析工作。但是,在 Electron 下运行时,情况会发生变化。
你的静态内容通常使用相对路径,如
./picture.jpg
,Electron 将使用file
协议(protocol)而不是HTTP
协议(protocol)并在根路径下找到文件,如C://.//
。所以像./picture.jpg
这样的静态内容将不会被正确加载。通过自定义
interceptFileProtocol()
,所有静态内容的请求都将指向您的工作目录,而不是 Windows(或其他操作系统)的根目录。
最后,我不确定它是否是所有 Electron 项目的好解决方案,但是如果你已经有一个 React
项目(或其他一些 SPA)并且想用 Electron package 它,这个解决方案可以使用。
关于javascript - 在 Electron 中提供静态文件(React 应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204774/