Webpacker Assets Demo
In general, rails/webpacker is a significant improvement over rails/sprockets for managing JavaScript assets, but it's generally just as capable at managing your fonts, CSS, and image assets as well. The documentation on how to accomplish this is probably not very clear to Rails developers without prior experience using Webpack.
Set up
$ bundle
$ rails s
Once the server is running, visit localhost:3000. You should see something like this:
Loading an image
First, this repo demonstrates loading an image:
- Storing an image where Webpack's
file-loader can find it
(
/app/javascript/images
in this case) - Importing that image from JavaScript being compiled by Webpack, which will add it to the public/packs/manifest.json. This exposes the asset to helper methods in Rails like asset_pack_path
- The value assigned by
import testDoubleSvg from '../images/test-double.svg'
will be the root-relative path of the file, including the hash fingerprint on the file name
Check out this commit for more detail.
Compiling styles via Webpacker instead of Sprockets
Second, this repo shows how to compile your styles (SCSS in this case) using
Webpacker instead of Sprockets. I suspect doing this would help lots of teams
drop their Sprockets dependency, which in turn speed up rake assets:precompile
quite a bit at deploy-time, since webpacker:compile
would overtake the command
outright.
- Put your style entry point somewhere (I chose
app/javascript/css/application.css
) - Again, import the styles somewhere from your JavaScript. This is truly a
silly step, but it's necessary in order to get it added to the manifest and
thereby linkable from your ERB template. In
app/javascript/packs/application.js
this is as simple asimport '../css/application.scss'
. There's no point assigning the import to something since we're only loading it for the side effect (ugh) - Finally, we can reference the template from our layout with:
<%= stylesheet_pack_tag 'application' %>
Here is the relevant commit.