What's the correct way to serve production react bundle.js built by webpack?

匆匆过客 提交于 2019-11-29 01:07:03

问题


I have an app with simple routes. It works fine when I use webpack development server. Now, I want to deploy it to my production server. So I built bundle.js. However, I am not sure what's the correct way to serve the file on the server.

Most blog posts stop at building bundle.js or deploy it to heroku or nodejutsu. What should I do if I want to serve it on my own server?

I tried serving the file on express server, but I'm getting this error in the browser (this same route works fine with webpack-dev-server).
http://localhost:3000/app
Cannot GET /app

I have simple route like this. Landing page at / works fine, but I can't access /app route

var Routes = () => (
    <Router history={browserHistory}>
        <Route path="/" component={Landing}>
        </Route>
        <Route path="/app" component={App}>
        </Route>
    </Router>
)

Here is my server.js. I put bundle.js, index.html in ./public

app.use(express.static('./public'));
app.listen(port, function () {
    console.log('Server running on port ' + port);
});

回答1:


You need to declare a "catch all" route on your express server that captures all page requests and directs them to the client. First, make sure you're including the path module on your server:

var path = require('path');

Then, put this before app.listen:

app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname, 'public/index.html'));
});

This assumes you're inserting bundle.js into index.html via a script tag.



来源:https://stackoverflow.com/questions/35928766/whats-the-correct-way-to-serve-production-react-bundle-js-built-by-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!