如何使electron打包時使用另外一個路由

問題描述

electron使用react全家桶寫的項目,想打開一個另外窗口,如設置界面.我們已經寫在另外一個路由下,如/settings路由

在開發環境下我們可以直接使用,如下顯示,基本沒有問題

mainWindow.loadURL('http://localhost:8888/#/settings')
可是在打包時候,我們打包後生成的靜態資源都以file協議被讀取,如果直接這樣是不行的 mainWindow.loadURL(url.format({ pathname: path.join(__dirname,
'/dist/index.html/#/settings'), protocol: 'file:', slashes: true, })) 那麼怎麼辦呢,經過查閱nodejs,url模塊文檔, 我們可以加一個hash屬性,如下 mainWindow.loadURL(url.format({ pathname: path.join(__dirname, '/dist/index.html'), protocol: 'file:', slashes: true, hash: "settings" })) 這樣就可以完美解決啦! 注意,在electron下,必須使用react-router-dom下的HashRouter,否則在打包時候的環境下有問題 遇到的坑 使用了異步組件(代碼分割) 使用如下進行代碼分割 import AsyncComponent from "@app/components/asyncComponent"; ... export class App extends React.Component<any, any> { render() { return ( <HashRouter> <Switch> <Route exact path="/setting" component={AsyncComponent(() => import(/*webpackChunkName:'setting'*/"@app/containers/setting/Index"))}/> <Route path="/" component={Home}/> </Switch> </HashRouter> ); } } 最後按文章使用這個settings路由的時候,顯示錯誤,查看開發者工具,發現加載的路徑有問題. "file:///Users/tao/Documents/electron/helloEle/dist/.js/settings.chunkc54aae4.js" 其中多了一個,自然而然想到webpack的output中的publicPath設置了這個"." 那麼首頁爲什麼是正常的呢,再來看看index.html中生成的路徑 <script type=text/javascript src=./js/vendor.chunk59e4497.js?75e513edd0c9ef261c87></script> 取得是相對路徑,由electron處理相對路徑,這樣沒毛病. 但是這個settings的js是有webpack給我們加上去的,而且坑爹的把路徑拼成了這樣(其實也不怪他),那麼有辦法處理這個問題嗎? 那肯定,否則還寫什麼.只需簡單的把publicPath改成""就行了.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章