【问题标题】:Hash routing in production throwing file not found error未找到生产抛出文件中的哈希路由错误
【发布时间】:2020-12-01 17:26:35
【问题描述】:

我正在使用 electron-react-boilerplate 并想在新的 BrowserWindow 中打开一个组件。关于如何执行此操作有多个问题和答案,但在打包应用程序后它们都不起作用。

我找到的问题/答案:

在我的组件中,我尝试使用以下几行来打开一个通往不同路线的新窗口。

wind.loadURL(`file://${__dirname}/app.html#/video`)

wind.loadURL(`file://${Path.join(__dirname, '../build/app.html#/video')}`)

wind.loadURL(`file://${Path.join(__dirname, '../build/index.html#/video')}`)

第一个在运行 yarn dev 时有效,但在生产环境中无效。他们都为各自的路径抛出 ERR_FILE_NOT_FOUND。

我的路线是这样设置的:

export default function Routes() {
  return (
    <App>
      <HashRouter>
        <Route exact path={routes.HOME} component={HomePage} />
        
        <Route path={routes.VIDEO} component={VideoPage} />
      </HashRouter>
    </App>
  );
}

在使用 React 的路由器打开一个新的 BrowserWindow 时,有没有一种简单的方法来允许路由?

【问题讨论】:

    标签: reactjs electron electron-react-boilerplate


    【解决方案1】:

    时机很好。过去几天我在同一条船上,只是想通了。除了,我没有像你那样改成HashRouter。相反,我将所有路由内容保留为默认的electron-react-boilerplate,例如ConnectedRouter。也许任何一种方式都有效。

    https://github.com/electron-react-boilerplate/electron-react-boilerplate/issues/1853#issuecomment-674569009

    __dirname 仅适用于开发。我使用 DebugTron 检查为每个资源加载了哪些 URL,它是 file://path/to/app.asar/something。然后我想出了如何到达asar的路径。无论应用程序位于何处,这对我在开发和生产中都有效。您还需要设置nodeIntegration: true。在 macOS 上测试。

    const electron = require("electron")
    //...
    win.loadURL(`file://${electron.remote.app.getAppPath()}/app.html#/yourroutename`)
    

    如果有人也想知道如何加载另一个页面并将参数传递给它,更完整的示例:

    import routes from '../constants/routes.json'
    const electron = require("electron")
    // ...
    var win = new BrowserWindow({
      width: 400, height: 400,
      webPreferences: { nodeIntegration: true }
    })
    win.loadURL(`file://${electron.remote.app.getAppPath()}/app.html#${routes["ROOM"]}?invitationCode=${encodeURIComponent(code)}`)
    win.show()
    

    并在组件中加载路由:

    const queryString = require('query-string')
    // ...
    constructor(props) {
      super(props)
      const params = queryString.parse(location.hash.split("?")[1])
      this.invitationCode = params.invitationCode
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2013-09-04
      • 2023-02-16
      相关资源
      最近更新 更多