[英]Webpack not compiling when not in the root url
I have the following output section specified in my webpack.config.js: 我在webpack.config.js中指定了以下输出节:
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '/'
},
I then have my express server set up like this: 然后,我的快速服务器设置如下:
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const config = require('./webpack.config.dev');
const app = express();
const compiler = webpack(config);
var host = config.host || 'localhost';
var port = (Number(config.port) + 1) || 4040;
const serverConfig = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true},
publicPath: '/'
};
app.use(express.static(__dirname + '/public'));
app.use(require('webpack-dev-middleware')(compiler, serverConfig));
app.use(require('webpack-hot-middleware')(compiler));
const indexFile = path.join(__dirname, './client/public/index.html');
app.use(express.static(__dirname + './build'))
app.get('*', function(req, res) {
console.log(req.originalUrl);
res.sendFile(indexFile);
});
app.listen(4040, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:4040');
});
When I am at the root url, ie '/' then the bundle.js file is rendered: 当我在根URL时,即'/',然后渲染bundle.js文件:
<script src="bundle.js"/>
But when I navigate to a non root url and refresh the page, webpack does not render the bundle.js and the script tag is not added. 但是,当我导航到非根URL并刷新页面时,webpack不会呈现bundle.js,并且不会添加脚本标记。
By default only the root serves index.html
. 默认情况下,只有root服务于index.html
。 You need to enable historyApiFallback in your dev server config historyApiFallback: true
. 您需要在dev服务器配置historyApiFallback: true
启用historyApiFallback。 That way the server will serve index.html in all routes. 这样服务器将在所有路由中提供index.html。
Turns out this more convoluted because I am using the HtmlWebpackPlugin
, this fixes it: 事实证明这更复杂,因为我正在使用HtmlWebpackPlugin
,这解决了它:
var express = require('express');
var app = express();
var webpack = require('webpack');
var path = require('path');
var compiler = webpack(require('./webpack.config.js'));
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: '/'
}));
app.use('*', function (req, res, next) {
var filename = path.join(compiler.outputPath,'index.html');
compiler.outputFileSystem.readFile(filename, function(err, result){
if (err) {
return next(err);
}
res.set('content-type','text/html');
res.send(result);
res.end();
});
});
app.listen(3000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.