我尝试使用 webpack-dev-middleware 作为中间件。我按原样捆绑在内存中并提供JS输出文件,但是当我保存时它不会热重载。
有什么想法吗?
你会
想要使用 https://www.npmjs.com/package/webpack-hot-middleware 或类似的东西。
你应该使用 webpack-hot-middleware
. 这是一个工作示例。我希望它有所帮助。
对于您的 webpack 配置(我们称之为 webpack.config.dev
):
const path = require('path');
const webpack = require('webpack');
const distPath = path.resolve(__dirname, '../dist');
const srcPath = path.resolve(__dirname, '../src');
module.exports = {
context: srcPath,
target: 'web',
entry: [
'react-hot-loader/patch',
// activate HMR for React
// bundling the client for webpack-dev-server
// and connect to the provided endpoint
'webpack-hot-middleware/client',
'./client/index.js'
// the entry point of your app
],
output: {
filename: 'app.js',
// the output bundle
path: distPath,
publicPath:'/static/',
// necessary for HMR to know where to load the hot update chunks
pathinfo: true
},
module: {
rules: [
// eslint checking before processed by babel
{test: /.js$/, enforce: 'pre', loader: 'eslint-loader', exclude: /node_modules/},
// babel
{test: /.js$/, use: [{loader: 'babel-loader'}], exclude: /node_modules/}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
// enable HMR globally
new webpack.DefinePlugin({ "process.env": { NODE_ENV: '"development"' } })
]
};
对于服务器(称为 index.dev.js
):
import path from 'path';
import express from 'express';
import React from 'react';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { renderToString } from 'react-dom/server';
// the above file
import webpackConfig from '../../webpack/webpack.config.dev';
// myown react Html component
import Html from '../server/Html';
const app = express();
app.use(express.static(path.join(__dirname, '..', './public')));
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
quiet: true,
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: { colors: true }
}));
app.use(webpackHotMiddleware(compiler));
app.get('*', (req, res) =>
res.status(200).send(`<!doctype html>${renderToString(
<Html />)}`
// This is my own Html react component. You can send a static html file here as well.
)
);
app.listen(3000, (err) => {
if (err) {
console.error(err);
return;
}
console.info('Demo app listening on port 3000');
});
最后,我用 babel-watch 来称呼它:
"scripts": {
"start:dev": "rm -f ./dist/* && ./node_modules/.bin/babel-watch ./src/server/index.dev.js -w ./src/server",
},