我找到了另一种解决方案,而无需使用express
或serve-static
,只有我们做 需要定制Electron内置interceptFileProtocol()
来提供静态内容。
代码:(main.js)
(我用的是electron-quick-start为电子模板)
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
相对路径,电子将使用file
协议,而不是HTTP
协议下找到根路径中的文件一样C://.//
。因此,像./picture.jpg
这样的静态内容将无法正确加载。
通过自定义interceptFileProtocol()
,所有静态内容的请求将被指向您的工作目录而不是Windows(或其他操作系统)根目录。
最后,我不知道它是否是所有电子项目的一个很好的解决方案,但如果你已经有了一个React
项目(或其他一些SPA),并希望与电子把它包起来,此解决方案将是罚款使用。
这对我有用,但后来在索引index.html中使用相对路径时遇到了索引js文件的问题。通过使用'require('electron')。remote.app'获取应用程序路径,最终需要使用绝对路径。getAppPath()' –