When does Webpacker compile?

Posted . Visible to the public.

Webpack builds can take a long time, so we only want to compile when needed.

This card shows what will cause Webpacker (the Rails/Webpack integration) to compile your assets.

When you run a dev server

While development it is recommended to boot a webpack dev server using bin/webpack-dev-server.

The dev server compiles once when booted. When you access your page on localhost before the initial compilation, the page may load without assets.

The dev server will detect any changes to your JavaScript and CSS and re-compile automatically. When it is done automatically any browser window showing your page on localhost will automatically reload the get the new assets. You cannot speed up this process by reloading manually before the dev server has finished re-compiling, you will just reload the same old assets.

When you render HTML without a dev server

When you don't have a dev server running and call any helper that accesses asset paths (e.g. javascript_pack_tag or image_tag), Rails will compile your entire assets within its process before that helper returns.

This will cause your helper to freeze for many seconds. Since Webpack needs to boot from scratch and re-compile after every change it can make reloading the page extremely slow. For this reason it is recommended to use a dev server during development.

This behavior can be disabled by the compile: true setting in config/webpacker.yml.

Note that this can also cause your RSpec specs to compile assets if you have any view specs, if a model refers to a compiled image path, or similar. See this card for a way to mitigate the damage.

When you tell Webpacker to compile

You can call bin/webpack explicitely to compile files to public/packs.

When deploying with Capistrano this is done automatically by the compile:assets task.

Why Webpacker sometimes does not re-compile

Webpacker only compiles when files changed. It detects changes by making a SHA1 digest over the contents of the following files:

  • app/webpacker/**/* (your Webpacker's source_path)
  • yarn.lock
  • package.json
  • config/webpack/**/*

If you make changes to any other files, Webpacker will not recompile.

The digest of the last compilation is cached in tmp/cache/webpacker/last-compilation-digest-test (replace -test with your environment). You can remove that file to force a re-compile.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2021-04-21 13:14)