All Projects → testdouble → webpacker-assets-demo

testdouble / webpacker-assets-demo

Licence: other
A demo repo to show how to reference images and styles when using Webpacker instead of Sprockets

Programming Languages

ruby
36898 projects - #4 most used programming language
HTML
75241 projects
javascript
184084 projects - #8 most used programming language
SCSS
7915 projects

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:

screenshot of working app

Loading an image

First, this repo demonstrates loading an image:

  1. Storing an image where Webpack's file-loader can find it (/app/javascript/images in this case)
  2. 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
  3. 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.

  1. Put your style entry point somewhere (I chose app/javascript/css/application.css)
  2. 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 as import '../css/application.scss'. There's no point assigning the import to something since we're only loading it for the side effect (ugh)
  3. Finally, we can reference the template from our layout with: <%= stylesheet_pack_tag 'application' %>

Here is the relevant commit.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].