我很难在我启动它时弄清楚我的服务器返回错误的原因。我没有使用webpack-dev-server,因为它没有编译JS文件所以我决定创建自己的服务器。当我打开浏览器时,它显示一条错误消息:
server.js
:
var webpack = require('webpack'),
path = require('path'),
express = require('express'),
devMiddleware = require('webpack-dev-middleware'),
hotMiddleware = require('webpack-hot-middleware'),
config = require('./webpack.config'),
app = express(),
host = '127.0.0.1',
port = 8000;
var middleware = devMiddleware(webpack({
entry: path.join(__dirname, 'app/src/main.js'),
output: {
path: '/',
}
}), {
noInfo: true,
publicPath: config.output.publicPath,
index: path.join(__dirname, 'app/index.html'),
stats: {
colors: true
}
});
app.use(middleware);
app.use(hotMiddleware(webpack(config)));
app.get('/', function(req, res) {
res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'app/index.html')));
res.end();
});
app.listen(port, host, function(err) {
if (err) {
console.error(err);
}
console.log('Listening on ' + host + ':' + port);
});
我不明白为什么会这样。也许我错过了许多重要的插件或依赖项来使它成功,就像react-hot-loader一样?或者这没关系?
答案 0 :(得分:1)
从我所看到的情况来看,您不应该使用middleware.fileSystem.readFileSync()
来处理index.html
的请求(这不是您的捆绑包的一部分)。
只需使用fs.readFileSync()
或最好使用res.sendFile()
:
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'app/index.html'));
});