如何允许 webpack-dev-server 允许来自 react-router 的入口点 [英] How to allow for webpack-dev-server to allow entry points from react-router
问题描述
我正在创建一个应用程序,在开发中使用 webpack-dev-server 和 react-router.
I'm creating an app that uses webpack-dev-server in development alongside react-router.
似乎 webpack-dev-server 是围绕这样一个假设构建的,即您将在一个地方(即/")有一个公共入口点,而 react-router 允许无限数量的入口点.
It seems that webpack-dev-server is built around the assumption that you will have a public entry point at one place (i.e. "/"), whereas react-router allows for an unlimited amount of entry points.
我想要 webpack-dev-server 的好处,尤其是热重载功能,这对生产力很有帮助,但我仍然希望能够加载 react-router 中设置的路由.
I want the benefits of the webpack-dev-server, especially the hot reloading feature that is great for productivity, but I still want to be able to load routes set in react-router.
如何实现它以便他们一起工作?你能在 webpack-dev-server 前面运行一个快速服务器,以允许这种方式吗?
How could one implement it such that they work together? Could you run an express server in front of webpack-dev-server in such a way to allow this?
推荐答案
我设置了一个代理来实现这个:
I set up a proxy to achieve this:
您有一个常规快递网络服务器,可以在任何路线上提供 index.html,除非它是资产路线.如果是资产,则请求会被代理到 web-dev-server
You have a regular express webserver that serves the index.html on any route, except if its an asset route. if it is an asset, the request gets proxied to the web-dev-server
您的 react hot 入口点仍将直接指向 webpack 开发服务器,因此热重载仍然有效.
your react hot entrypoints will still point directly at the webpack dev server, so hot reloading still works.
假设您在 8081 上运行 webpack-dev-server,在 8080 上运行代理.您的 server.js 文件将如下所示:
Let's assume you run webpack-dev-server on 8081 and your proxy at 8080. Your server.js file will look like this:
"use strict";
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./make-webpack-config')('dev');
var express = require('express');
var proxy = require('proxy-middleware');
var url = require('url');
## --------your proxy----------------------
var app = express();
## proxy the request for static assets
app.use('/assets', proxy(url.parse('http://localhost:8081/assets')));
app.get('/*', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
# -----your-webpack-dev-server------------------
var server = new WebpackDevServer(webpack(config), {
contentBase: __dirname,
hot: true,
quiet: false,
noInfo: false,
publicPath: "/assets/",
stats: { colors: true }
});
## run the two servers
server.listen(8081, "localhost", function() {});
app.listen(8080);
现在像这样在 webpack 配置中创建入口点:
now make your entrypoints in the webpack config like so:
entry: [
'./src/main.js',
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:8081'
]
注意直接调用 8081 进行热重载
note the direct call to 8081 for hotreload
还要确保将绝对网址传递给 output.publicPath
选项:
also make sure you pass an absolute url to the output.publicPath
option:
output: {
publicPath: "http://localhost:8081/assets/",
// ...
}
这篇关于如何允许 webpack-dev-server 允许来自 react-router 的入口点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!