6
4

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 3 years have passed since last update.

【Rails + Webpacker】assetsの画像を使いたい! Vue.jsで画像を表示できるまで

Posted at

RailsとWebpackerで開発している時に、画像どうやって読み込むのかなと思って調べてみた記録です。

WebpackerのREADMEをのぞいてみる

WebpackerのREADMEの Paths > resolved を参照してみると、assetsをもつアプリとimagesを共有したいときは、webpacker.ymlresolved_pathsと書いて読み込める、とあります。今回はこれに習って実装しています。

config/webpacker.yml
resolved_paths: ['app/assets']

ただし、コンパイルの速度に影響アリ

以下にあるように…

Please be careful when adding paths here otherwise it will make the compilation slow, consider adding specific paths instead of whole parent directory if you just need to reference one or two modules

でかいディレクトリ単位で読み込むとコンパイルが遅くなる、ということのようです。表示速度を気にする場合は注意したいです。

実装例

webpacker.ymlにpathをかく

上でみたように webpacker.ymlに記述していきます。今回はassets/images配下しか必要としていないので、先ほどの注意点も考慮してimagesまでpathを指定してみました。

config/webpacker.yml
  resolved_paths: ['app/assets/images']

Vue.jsで使うには

今回は、Vue.jsのコンポーネントで読み込みたかったので、一緒に書いておきます。

sample.vue
<template>
  <div>
    <!-- imgタグでsrcに"~"をつけてimportしたファイルを指定する -->
    <img src="~logo.svg" /> 
  </div>
</template>

<script>
  import 'logo.svg'; // ここでimport
</script>

こうやって書いてみるととってもシンプルですね。

以上、少しでも参考になれば嬉しいです。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?