Help us understand the problem. What is going on with this article?

webpackerでcssとimagesを参照したい

webpackerを新規で導入した時につまずいたのでメモ

構成

webpacker のREADMEと同じ構成で試してみた。

ディレクトリ構成

app/javascript:
  ├── packs:
  │   # only webpack entry files here
  │   └── application.js
  └── src:
  │   └── application.css
  └── images:
      └── logo.svg

先に結論

application.jsに以下を追記

app/javascript/packs/application.js

import '../src/application.css'
const images = require.context('../images/', true)

erbから呼び出し

<%= stylesheet_pack_tag 'application' %>
<%= image_pack_tag 'images/logo.svg' %>

# READMEではこのように呼べるよと書いてますね。
<link rel="prefetch" href="<%= asset_pack_path 'application.css' %>" />
<img src="<%= asset_pack_path 'images/logo.svg' %>" />

webpackでbuild

$ ./bin/webpack

背景

READMEの構成でapplication.cssを配置してbuild後、参照するとapplication.cssが見つからないと言われた。

Webpacker::Manifest::MissingEntryError in TopPages#index
Showing /Users/XXX/app/{app_name}/app/views/layouts/application.html.erb where line #9 raised:

Webpacker can't find application.css in /Users/XXX/app/{app_name}/public/packs/manifest.json. Possible causes:

出力先をみてみると確かにない。。

$ ll public/packs/
total 40
-rw-r--r--  1 XXX  staff  5598 12  5 00:42 application-a5d1ad856f093264b17a.js
-rw-r--r--  1 XXX  staff  4941 12  5 00:42 application-a5d1ad856f093264b17a.js.map
-rw-r--r--  1 XXX  staff   236 12  5 00:42 manifest.json

manifest.jsonをみてもない。。

$ cat public/packs/manifest.json
{
  "application.js": "/packs/application-a5d1ad856f093264b17a.js",
  "application.js.map": "/packs/application-a5d1ad856f093264b17a.js.map"
}

よくよく調べてREADMEを読んでみると

README:
If you have styles imported in your pack file, you can link them by using stylesheet_pack_tag
訳:
packファイルでスタイルシートがインポートされる場合は、stylesheet_pack_tagでリンクできます。

な、なるほど。

ということでした。

参考:

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away