Lesson Weekend

As we write code and add new assets to our application, our dist folder will get cluttered. webpack isn't going to automatically clean up after us. We need to add another plugin to do that. Fortunately, that's easy. We can install it like this:

$ npm install [email protected] --save-dev

Then simply add the plugin to our configuration file:

webpack.config.js
...
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // new line

module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new CleanWebpackPlugin(), // new line
    new HtmlWebpackPlugin({
      title: 'Shape Tracker',
      template: './src/index.html',
      inject: 'body'
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  }
};

We've added two lines to our webpack.config.js file. The new lines have comments to indicate where they are.

Hopefully this pattern is starting to look familiar.

  • First we require the new plugin and save it in a variable.
  • Then we add it to module.exports in the plugins section.
  • We create a new instance of the plugin and then specify that we'd like our dist folder cleaned out.

We could configure this plugin to clean multiple directories and exclude specific files but we'll keep it simple. Now, when we run $ npm run build, webpack will automatically clean out the contents of our dist folder before creating new bundle files.

Lesson 15 of 48
Last updated more than 3 months ago.