demo地址: https://github.com/Lkkkkkkg/webpack-demo
上次使用 webpack-dev-serve : https://blog.csdn.net/qq593249106/article/details/84922572
当前目录结构 :
|- /dist //用于放打包后文件的文件夹
|- app.bundle.js //出口文件
|- print.bundle.js //出口文件
|- index.html //模板文件
|- /node_modules
|- /src //用于放源文件的文件夹
|- index.js //入口文件
|- print.js
|- package.json
|- webpack.config.js //webpack配置文件
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js'
// print: './src/print.js'
},
devtool: 'inline-source-map', // 不同选项适用于不同环境
devServer: {
contentBase: './dist', //将dist目录下的文件(index.html)作为可访问文件, 如果不写这个参数则默认与webpack.cofig.js的同级目录
port: 8080 //端口号设为8080, 默认也是8080
},
plugins: [ //webpack 通过 plugins 实现各种功能, 比如 html-webpack-plugin 使用模版生成 html 文件
new CleanWebpackPlugin(['dist']), //设置清除的目录
new HtmlWebpackPlugin({
filename: 'index.html', //设置生成的HTML文件的名称, 支持指定子目录,如:assets/admin.html
})
],
output: {
filename: '[name].bundle.js', //根据入口文件输出不同出口文件
path: path.resolve(__dirname, 'dist')
}
};
这里把配置的 入口文件 print.js 给去掉了, 因为 print.js 被 入口文件 index.js 应用了
HMR(模块热替换)
模块热替换(Hot Module Replacement 或 HMR)是 webpack 提供的最有用的功能之一, 它允许在运行时更新各种模块, 而无需进行完全刷新
比如在这个现在修改 print.js 里面的内容, 使用 HMR 就可以只更新 print.js 里面的内容而不用重新加在整个页面
启用HMR
启用这个功能很简答, 只需要修改一下 webpack.config.js 的配置, 使用 webpack 内置的 HMR 插件就可以了
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require