Skip to content

Documentation asset.md update: Add needed require.context to use pack helpers #1969

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 18, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions docs/assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,26 +84,36 @@ import 'assets/stylesheets/bar'
## Link in your Rails views

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

```yml
app/javascript:
- packs
- hello_react.js
- styles
- hello_react.css
- app.js
- images
- calendar.png
```

```js
// app/javascript/packs/app.js (or any of your packs)

// import all image files in a folder:
require.context('../images', true)
```

```erb
<%= asset_pack_path 'hello_react.css' %>
<%# => "/packs/hello_react.css" %>
<%# Rails view, for example app/views/layouts/application.html.erb %>

<img src="<%= asset_pack_path 'media/images/calendar.png' %>" />
<% # => <img src="/packs/media/images/calendar-k344a6d59eef8632c9d1.png" /> %>

<img src="<%= asset_pack_path 'images/calendar.png' %>" />
<% # => <img src="/packs/images/calendar.png" /> %>
<%= image_pack_tag 'media/images/calendar.png' %>
<% # => <img src="/packs/media/images/calendar-k344a6d59eef8632c9d1.png" /> %>

<%= image_pack_tag 'images/calendar.png' %>
<% # => <img src="/packs/images/calendar.png" /> %>
<%# no path resolves to default 'images' folder: %>
<%= image_pack_tag 'calendar.png' %>
<% # => <img src="/packs/media/images/calendar-k344a6d59eef8632c9d1.png" /> %>
```

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).