M
M
Marat Linberg2020-04-16 17:11:28
JavaScript
Marat Linberg, 2020-04-16 17:11:28

How to configure deletion of the old bundle with webpack -watch?

Hello!
In general, such a problem: there is a /build folder, the webpack collects the assembly into this folder. If you build once (via the webpack command), then everything works fine - the old assembly is cleared.
If you collect on every file change (via the webpack -w command), then webpack collects the assembly, but the old assembly is not cleared.

Here is the webpack config

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');

module.exports = {
  context: __dirname,
    //heng entry file
  entry: "./app/app.js",
  output: {
    path: __dirname + "/build",
    filename: "bundle.[hash].js",
    chunkFilename : "../build/chunks/[hash].[chunkhash].js"
  },
  optimization: {
    minimizer: [
      new TerserJSPlugin({}), 
      new OptimizeCSSAssetsPlugin({}),
    ],
    splitChunks: {
      cacheGroups: {
        common_vendors: {
          test: /([\\/]app[\\/]core)|([\\/]node_modules[\\/])/,
          name: 'vendors', // имя чанка
          chunks: 'initial',
          enforce: true,
          filename: '[name].[chunkhash].js'
        }
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
        minify: { collapseWhitespace: true },
        template: 'app/index.html',  
        filename: './../index.html'
    }),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: 'app.[hash].css'
    })
  ]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dark_king_13, 2020-04-17
@dark_king_13

using -watch is not the best option. It's better to use webpack-dev-server for sites without a backend, or set up HMR for a server on express. There are many articles on the net about this. This will keep your build in memory and easy to update, rather than in a folder on disk. In a folder to collect only for production.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question