2017-09-05 29 views
0

我已經構建了一個具有Express後端和React前端的Web應用程序。Express:在子路由上提供Webpack捆綁

無論何時向Express服務器發出請求,它都會首先檢查URL是否與任何後端路由匹配,如果不匹配,則將使用Webpack生成的React包發送到客戶端(其中URL路由由React路由器)。

這適用於所有基本路線。但是,一旦發出對子路由的請求(例如/foo/bar),Express就會正確服務index.html,但似乎尋找目錄foo來服務bundle.js,在這種情況下,這是不受歡迎的行爲,並且會導致錯誤,因爲文件沒有在那裏找到。對於JS文件,這可以通過使用相對路徑來修復,但對於由Webpack處理的圖像來說問題仍然存在。

有沒有人知道這個解決方案?

server.js:

server.listen(port,() => { 
    // set up API routes 
    server.use('/api/auth', require(...)); 
    server.use('/api/users', require(...)); 

    // serve public files (JavaScript bundle, images, etc.) 
    server.use(express.static(path.join(__dirname, '../client', 'public'))); 

    // serve index.html on all other routes 
    server.get('*', (request, response) => { 
     response.sendFile(path.join(__dirname, '../client', 'public', 'index.html')); 
    }); 
}); 

的index.html:

import someIcon from '../public/img/someIcon.svg'; 
... 
<img src={someIcon}> 

的WebPack配置::

module.exports = { 
    entry: './client/index.jsx', 
    output: { 
     path: path.join(__dirname, 'client/public'), 
     filename: 'bundle.js' 
    }, 
    module: { 
     rules: [ 
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }, 
      { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, 
      { test: /\.(jpe?g|png|gif|svg)$/, loader: 'file-loader?name=img/[name].[ext]' } 
     ] 
    }, 
    resolve: { 
     extensions: ['.js', '.jsx'] 
    } 
}; 
在陣營成分的圖像導入

<!DOCTYPE html> 

<html> 
    <head> 
     ... 
    </head> 

    <body> 
     <div id="root"></div> 
     <script src="/client-bundle.js"></script> 
    </body> 
</html> 

實施例

我的文件結構:

/app 
    /client 
     /components 
      /SomeComponent.jsx 
     /index.jsx 
     /public 
      /index.html 
      /bundle.js 
      /img 
       /someIcon.svg 
    /server 
     /server.js 
+0

只需使用絕對路徑'SRC =「/客戶bundle.js」' – Molda

+0

@Molda我已經試過這一點,它適用於JS文件,圖像路徑將被替換,但不是f或圖像 – Baleb

+0

你可以在'src =「???」'中顯示你正在嘗試什麼的例子,你的文件夾結構中的圖像在哪裏? – Molda

回答

1

您可以設置服務器的公共路徑中的WebPack配置。如果您設置的公共路徑,然後將的WebPack與公共path.In您wepack設置的公共路徑替換圖片和其他文件的路徑,

output: { 
     path: path.join(__dirname, 'client/public'), 
     publicPath: "http://localhost:3000/", 
     filename: 'bundle.js' 
    }, 

而且在你的文件加載器,你可通過設置name=img/[name].[ext]

所以上述配置

http://localhost:3000/img/someIcon.svg