demo17 clean-webpack-plugin (清除模式)

1.爲何須要自動清除 dist 文件夾

在以前的 demo 中,webpack 打包後會在根目錄下自動建立 dist 目錄,而且把生成的文件輸出到 dist 下。javascript

當配置的輸出包名含有 [hash] 時,hash值會隨着文件內容的改變而改變。css

所以,咱們須要在下一次 webpack 打包輸出以前,把 dist 目錄清空。html

clean-webpack-plugin 插件就能幫你作到。java

2.clean-webpack-plugin

clean-webpack-plugin 能夠實現 webpack 每次打包以前,清空指定目錄。webpack

注意: clean-webpack-plugin 插件應該放在 plugins 的最後,由於 webpack 的插件執行順序是從後往前執行的。 好比:git

plugins: [
    new HtmlWebpackPlugin(),
    new MiniCssExtractPlugin(),
    new CleanWebpackPlugin(["dist"]) // 需放在最後一個
  ]
複製代碼

3.安裝相關依賴

npm install -D clean-webpack-plugin
npm install -D css-loader style-loader
npm install -D html-webpack-plugin webpack 
複製代碼

4.目錄結構

// `--` 表明目錄, `-` 表明文件
  --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');
複製代碼

5.編寫webpack配置文件

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"])
  ]
};
複製代碼

6.執行打包命令

(默認你已經安裝了全局 webpack 以及 webpack-cli )app

webpack
複製代碼

7.驗證打包結果

每次進行 webpack 打包都會先清除 dist 目錄

8.源碼地址

demo 代碼地址: github.com/SimpleCodeC…

倉庫代碼地址(及目錄): github.com/SimpleCodeC…

相關文章
相關標籤/搜索