在以前的 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…