Ale*_*cic 7 javascript node.js reactjs electron
我正在开发一个项目,我需要在Electron中构建一个桌面应用程序.大多数功能都将在React中构建,但是我们需要集成第三方静态HTML杂志.我需要一些关于如何做到这一点的建议.我目前正在构建一个概念验证应用程序,我将它基于此https://github.com/chentsulin/electron-react-boilerplate
我如何在/ static/I服务器静态HTML文件上添加它.我知道我可以在express中完成它,但我真的不想仅仅为了提供静态文件而包含整个express框架.
我正在看这个https://www.npmjs.com/package/serve-static但是没有想法如何将它集成到我的反应应用程序中并将其捆绑到电子应用程序中.
yez*_*322 12
我发现了另一个没有使用express或者解决方案的解决方案serve-static,我们只需要将内置的Electron定制interceptFileProtocol()为静态内容.
代码:(main.js)
(我使用电子快速启动作为电子模板)
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()
})
Run Code Online (Sandbox Code Playgroud)
参考: protocol.interceptFileProtocol()
解释:
通常,如果您将React应用程序作为普通网站运行,则所有静态内容都应由HTTP [GET]方法提供.虽然它们使用相对路径,但您的HTTP服务器将处理路径解析工作.
然而,当在Electron下运行时,事情会发生变化.
你的静态内容通常使用相对路径./picture.jpg,Electron将使用file协议而不是HTTP协议,并在根路径下找到文件C://.//.所以静态内容./picture.jpg不会正确加载.
通过自定义interceptFileProtocol(),所有静态内容的请求将指向您的工作目录而不是Windows(或其他OS)根目录.
最后,我不确定它是否适用于所有Electron项目,但如果你已经有一个React项目(或其他一些SPA)并想用Electron包装它,那么这个解决方案就可以使用了.
在你的主文件中有
\n\nconst app = require("app")\napp.on("ready", () => {\n ...\nRun Code Online (Sandbox Code Playgroud)\n\n在这里你可以像在node.js中一样启动服务器
\n\n const\xc2\xa0serveStatic\xc2\xa0=\xc2\xa0require(\'serve-static\')\n // or\n const\xc2\xa0express\xc2\xa0=\xc2\xa0require(\'express\')\n ...\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
7763 次 |
| 最近记录: |