如何为 webpack 构建的生产 react bundle.js 提供服务? [英] How to serve production react bundle.js built by webpack?

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

问题描述

我的应用程序在 webpack 开发服务器中运行良好.现在,我想将它部署到我的生产服务器.所以我构建了 bundle.js.我尝试在快速服务器上提供文件,但我无法访问除根 / 之外的 url.

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

和express app(我把bundle.jsindex.html放在./public中):

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.

推荐答案

您需要在 Express 服务器上声明一个捕获所有"路由,该路由捕获所有页面请求并将它们定向到客户端.首先,确保您在服务器上包含 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 构建的生产 react bundle.js 提供服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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