在以前的 demo 中,webpack 打包後會在根目錄下自動建立 dist 目錄,而且把生成的文件輸出到 dist 下。javascript
當配置的輸出包名含有 [hash]
時,hash值會隨着文件內容的改變而改變。css
所以,咱們須要在下一次 webpack 打包輸出以前,把 dist 目錄清空。html
clean-webpack-plugin 插件就能幫你作到。java
clean-webpack-plugin
能夠實現 webpack 每次打包以前,清空指定目錄。webpack
注意:
clean-webpack-plugin
插件應該放在plugins
的最後,由於 webpack 的插件執行順序是從後往前執行的。 好比:git
plugins: [
new HtmlWebpackPlugin(),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin(["dist"]) // 需放在最後一個
]
複製代碼
npm install -D clean-webpack-plugin
npm install -D css-loader style-loader
npm install -D html-webpack-plugin webpack
複製代碼
// `--` 表明目錄, `-` 表明文件
--demo17
--src
-app.js
-style.css
-index.html
-webpack.config.js
複製代碼
src/style.cssgithub
body {
background-color: red;
}
複製代碼
src/app.jsweb
const css = import('./style.css');
複製代碼
webpack.config.jsnpm
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = {
entry: {
app: "./src/app.js"
},
output: {
publicPath: __dirname + "/dist/", // 打包後資源文件的引用會基於此路徑
path: path.resolve(__dirname, "dist"), // 打包後的輸出目錄
filename: "[name]-[hash].bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
// css處理爲style標籤
use: [
"style-loader",
'css-loader'
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: '設置html的title',// 當設置了template選項後,title選項將失效
filename: "index.html",
template: "./index.html",
minify: {
// 壓縮選項
collapseWhitespace: true
}
}),
new CleanWebpackPlugin(["dist"])
]
};
複製代碼
(默認你已經安裝了全局 webpack 以及 webpack-cli )app
webpack
複製代碼
每次進行 webpack 打包都會先清除 dist 目錄
demo 代碼地址: github.com/SimpleCodeC…
倉庫代碼地址(及目錄): github.com/SimpleCodeC…