webpack學習(四):配置CleanWebpackPlugin
阿新 • • 發佈:2018-12-11
demo地址: https://github.com/Lkkkkkkg/webpack-demo
上次配置HtmlWebpackPlugin: https://blog.csdn.net/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 外掛