Skip to content

Commit 554221c

Browse files
klausbadeltgauravtiwari
authored andcommitted
Documentation asset.md update: Add needed require.context to use pack helpers (#1969)
* Add needed require.context to use pack helpers As discussed in #705, the documentation is missing the essential addition of require.context in your app js to make the `asset_pack_path` and `image_pack_tag` * updated to reflect 0b86cad and PR #1964
1 parent 818de9c commit 554221c

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

docs/assets.md

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -84,26 +84,36 @@ import 'assets/stylesheets/bar'
8484
## Link in your Rails views
8585

8686
You can also link `js/images/styles/fonts` used within your js app in views using
87-
`asset_pack_path` helper. This helper is useful in cases where you just want to
87+
`asset_pack_path` and `image_pack_tag` helpers. These helpers are useful in cases where you just want to
8888
create a `<link rel="prefetch">` or `<img />` for an asset.
8989

9090
```yml
9191
app/javascript:
9292
- packs
93-
- hello_react.js
94-
- styles
95-
- hello_react.css
93+
- app.js
9694
- images
9795
- calendar.png
9896
```
9997
98+
```js
99+
// app/javascript/packs/app.js (or any of your packs)
100+
101+
// import all image files in a folder:
102+
require.context('../images', true)
103+
```
104+
100105
```erb
101-
<%= asset_pack_path 'hello_react.css' %>
102-
<%# => "/packs/hello_react.css" %>
106+
<%# Rails view, for example app/views/layouts/application.html.erb %>
107+
108+
<img src="<%= asset_pack_path 'media/images/calendar.png' %>" />
109+
<% # => <img src="/packs/media/images/calendar-k344a6d59eef8632c9d1.png" /> %>
103110
104-
<img src="<%= asset_pack_path 'images/calendar.png' %>" />
105-
<% # => <img src="/packs/images/calendar.png" /> %>
111+
<%= image_pack_tag 'media/images/calendar.png' %>
112+
<% # => <img src="/packs/media/images/calendar-k344a6d59eef8632c9d1.png" /> %>
106113
107-
<%= image_pack_tag 'images/calendar.png' %>
108-
<% # => <img src="/packs/images/calendar.png" /> %>
114+
<%# no path resolves to default 'images' folder: %>
115+
<%= image_pack_tag 'calendar.png' %>
116+
<% # => <img src="/packs/media/images/calendar-k344a6d59eef8632c9d1.png" /> %>
109117
```
118+
119+
Note you need to add a `media/` prefix (not `/media/`) to any subfolder structure you might have in `app/javascript`. See more examples in the [tests](https://github.com/rails/webpacker/blob/0b86cadb5ed921e2c1538382e72a236ec30a5d97/test/helper_test.rb#L37).

0 commit comments

Comments
 (0)