webpack使用webpack-dev-middleware进行热重载
新手,刚开始学习webpack,想使用webdevserver,但定制性太差,于是研究了一下使用webpack-dev-middleware进行指定。
根据文档https://www.npmjs.com/package/webpack-hot-middleware
需要配置entry和output.
常规配置
entry: ['./src/main.js'],
output: {
path: path.resolve(__dirname, 'dist/'),
filename: '[name].[hash].js',
},
但在热重载中,文件是不存放在硬盘上的,而是使用了memory-fs模块存放在内存中的,因此原始规则不能使用了。
查看与webpack-dev-middleware配合需要使用到webpack-hot-middleware,在内存中使用时需要为入口文件添加一个'webpack-hot-middleware/client',
同时输出的文件也和原来不同,文件不再带有根目录,因此,Path和publicpath均需要修改,结果如下:
entry: {
app:[
'webpack-hot-middleware/client',
'./src/main.js'
],
},
output: {
path: '/',
// publicPath: '/'
},
同时还需要添加相应的热重载插件:
plugins:
let express = require('express'); let webpack = require("webpack"); const fs = require('fs') let app = express() let port; let webpackconfig = require('./build/webpack.dev.config'); webpackconfig(app) app.use(express.static('./static')); app.get('/', function(req, res, next){ next(); }) app.listen(port || 9999, function(e){ console.log(`server start at ${port}`); });
webpack.base.config.js
var webpack = require("webpack"); var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: ['./src/main.js'], output: { path: path.resolve(__dirname, 'dist/'), filename: '[name].[hash].js', }, module: { rules:[ { test: /\.js/, include:[path.resolve(__dirname,'src')], loader: 'babel', options: { presets: 'es2015', } }, { test: /\.vue/, loader: 'vue', }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { extensions: ['.vue','.js', 'json', ' '], alias: { 'components': './src/', } }, }
webpack.dev.config.js
let webpack = require("webpack");
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let devMiddleWare = require('webpack-dev-middleware');
let hotMiddleWare = require('webpack-hot-middleware');
let baseConfig = require('./webpack.base.config');
let devOption = {
entry: {
app:[
'webpack-hot-middleware/client',
'./src/main.js'
],
},
output: {
path: '/',
// publicPath: '/'
},
plugins: [
// new webpack.optimize.OccurenceOrderPlugin(),
// Webpack 2.0 fixed this mispelling
// new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html'
}),
]
}
module.exports = function(app){
let webpackconfig = Object.assign({}, baseConfig, devOption);// console.log(webpackconfig);
var compiler = webpack(webpackconfig);// console.log(compiler);
app.use(devMiddleWare(compiler,{
publicPath: webpackconfig.output.publicPath,
stats: {
colors: true,
chunks: false
}
}));
app.use(hotMiddleWare(compiler));
return app;
}