我在webpack.config.js中指定了以下输出节:
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '/'
},
然后我将我的快速服务器设置为:
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');
});
当我在根网址时,即' /'然后渲染bundle.js文件:
<script src="bundle.js"/>
但是当我导航到非根URL并刷新页面时,webpack不会渲染bundle.js并且不会添加脚本标记。
答案 0 :(得分:0)
默认情况下,只有根服务index.html
。您需要在dev服务器配置historyApiFallback: true
中启用historyApiFallback。这样服务器将在所有路由中提供index.html。
答案 1 :(得分:0)
事实证明这更复杂,因为我使用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);