如何服务于webpack构建的production react bundle.js? [英] How to serve production react bundle.js built by webpack?

查看:80
本文介绍了如何服务于webpack构建的production react bundle.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序在Webpack开发服务器中运行良好.现在,我想将其部署到我的生产服务器上.所以我建立了bundle.js.我尝试在快递服务器上提供文件,但是除根目录/之外,我无法访问其他网址.

My app works fine in webpack development server. Now, I want to deploy it to my production server. So I built bundle.js. I tried serving the file on express server, but I can't access urls other than the root /.

例如,这是我的反应路线:

For example, here is my react routes:

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

并快递应用程序(我在./public中放入了bundle.jsindex.html):

and express app (I put bundle.js and index.html in ./public):

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

着陆页http://localhost:3000/起作用.但是应用程序http://localhost:3000/app没有.相反,我出现了错误Cannot GET /app.

Landing page http://localhost:3000/ works. But the app http://localhost:3000/app doesn't. Instead, I got an error Cannot GET /app.

推荐答案

您需要在快递服务器上声明捕获所有"路由,该路由捕获所有页面请求并将其定向到客户端.首先,请确保在服务器上包含path模块:

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');

然后,将其放在app.listen之前:

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

这假设您要通过脚本标记将bundle.js插入index.html.

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

这篇关于如何服务于webpack构建的production react bundle.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆