demo地址: https://github.com/Lkkkkkkg/webpack-demo
上次配置HtmlWebpackPlugin: https://blog.youkuaiyun.com/qq593249106/article/details/84900169
继上次配置完 HtmlWebpackPlugin 之后, 发现 dist 目录下产生了很多个 bundle.js 文件:
当前目录结构:
|- /dist //用于放打包后文件的文件夹
|- app.bundle.js //这一次构建的出口文件
|- print.bundle.js //这一次构建的出口文件
|- bundle.js //前一次构建的出口文件
|- index.html //模板文件
|- /node_modules
|- /src //用于放源文件的文件夹
|- index.js //入口文件
|- print.js //入口文件
|- package.json
|- webpack.config.js //webpack配置文件
这是因为每次重构, 前一次的出口文件不会被清除, 所以就同时存在了前一次( bundle.js )和这一次的出口文件( app.bundle.js 和 print.bundle.js), 而前一次的 bundle.js 已经用不到了, 没有存在意义
清理 dist 文件夹
使用 CleanWebpackPlugin 插件可以在每次构建前都清楚 dist 文件夹, 这样每次构建完, dist 目录下只有会生成要用到的文件
安装CleanWebpackPlugin
npm install clean-webpack-plugin --save-dev
配置webpack.config.js
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'
},
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')
}
};
重新构建
终端输入 npm run build , 打开index.html:
输出没问题, 构建成功, 再看看此时的目录结构:
|- /dist //用于放打包后文件的文件夹
|- app.bundle.js //这一次构建的出口文件
|- print.bundle.js //这一次构建的出口文件
|- index.html //模板文件
|- /node_modules
|- /src //用于放源文件的文件夹
|- index.js //入口文件
|- package.json
|- webpack.config.js //webpack配置文件
可以发现前一次的 bundle.js 文件已经被清掉了, 成功配置了 CleanWebpackPlugin 插件