28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

webpackerでcssとimagesを参照したい

Last updated at Posted at 2018-12-04

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でリンクできます。

な、なるほど。
ということでした。

参考:

28
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?