1、下载
cnpm install webpack-dev-middleware -D
2、配置
const webpack = require('webpack');
const middleware = require('webpack-dev-middleware');
const config = require('../webpack.config'); 配置webpack
const compiler = webpack(config);
const express = require('express');
const app = express();
app.use(
middleware(compiler, {
// webpack-dev-middleware options
})
);
app.listen(3000, () => console.log('Example app listening on port 3000!'));
3、若报错Can't resolve 入口文件的错误
在webpack配置中添加上下文环境
module.exports = {
context:path.resolve(__dirname),
}
代码示例:
const webpack = require('webpack');
const middleware = require('webpack-dev-middleware');
const config = require('../webpack.config');
const compiler = webpack(config);
const express = require('express');
const app = express();
app.use(
middleware(compiler, {
// webpack-dev-middleware options
})
);
app.get('/us', (req, res) => {
res.json({ name: 'jeff' });
})
app.listen(3000, () => console.log('Example app listening on port 3000!'));