Rails Webpack public packs clean up assets

When using webpacker with Rails, webpack assets from public/packs folder usually occupy a lot of disk space. Thus, it is important to clean up disk space time to time or we can use clean webpack plugin to clean packs automatically.

Rails 6 supports webpacker by default. Rails 5.1 had merged webpacker in Rails and we had to use --webpacker option to use webpacker as an asset pipeline with Rails.

public/packs occupies huge disk space

As we have been using webpacker with Rails and compile directory as public/packs in development environment, every time server boots up or we make any changes to javascript files, it compiles webpack assets.

This occupies huge space. There are a couple of approaches that can be used to clean up such files.

1. Webpack clobber assets

One of the solution is to, clean up using rake task provided as given below.

bundle exec rails webpacker:clobber

This will clean up directory that is use for outputting compiled webpack assets. But, again this is a manual effort and we need to invoke this rake task often to clean up disk space.

Clean up webpack plugin

1. Add clean-webpack-plugin

Add clean-webpack-plugin as given below.

yarn add -D clean-webpack-plugin
2. Add plugin to development.js

We need to add this plugin to development.js.

# webpack/development.js
const CleanWebpackPlugin = require("clean-webpack-plugin")
const path = require("path")
const environment = require("./environment")

environment.plugins.append(
  "CleanWebpackPlugin",
  new CleanWebpackPlugin(["packs"], {
    root: path.resolve(__dirname, "../../public"),
    verbose: true
  })
)
module.exports = environment.toWebpackConfig()

Once this change is in place, whenever webpack compiles assets, it will only generate new files.

Thus, the directory won’t occupy a lot of space by not having older webpack compiled assets in the directory which are not required.

References