LoginSignup
0
0

More than 1 year has passed since last update.

vueファイルが表示されない問題

Last updated at Posted at 2021-09-19

既存RailsアプリにVue.jsを使用しフォロー機能を追加しました。
開発環境では無事にフォローボタンが表示されていましたが、
本番環境では表示されないという事案が発生。表示させるまでの経緯を振り返りたいと思います。

開発環境
windows10 home
Ruby 2.6.3
Ruby on Rails 5.2.6
vue.js 2.6.14

実現したいこと

開発環境では表示される
開発環境.png

問題点

本番環境では表示されない、、
vueを呼び出しているidの要素がElementsになく、下記のコードが表示される。

<!--function (e,n,r,o){return sn(t,e,n,r,o,!0)}-->

本番環境.png

?????
検索しても引っかからず、、
今まで要素が読み込まれないことがなかったので混乱しました。

原因究明

ファイル自体は読み込まれ、
idの要素のの中に入ると表示されない。

_follows.html.erb
<%= javascript_pack_tag 'relationship' %>

<%# 表示できる %>
<p>test</p>

<div id="relationship">
  <%# 表示できない %>
  <p>test</p>
  <% if current_user.id != user.id %>
    <relationship-button :follower-id="<%= current_user.id %>" :followed-id="<%= @user.id %>"></relationship-button>
  <% end %>
</div>

結論

ランタイムビルドのみをしていたので、完全ビルドに切り替えることによって、
テンプレート文字列を JavaScript レンダリング関数にコンパイルする。
本番環境では完全ビルドが必要

公式ドキュメント参照
https://jp.vuejs.org/v2/guide/installation.html#%E3%81%95%E3%81%BE%E3%81%96%E3%81%BE%E3%81%AA%E3%83%93%E3%83%AB%E3%83%89%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6

webpack.config.js
module.exports = {
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  }
}

それをjsファイルにインポート

relationship.js
import Vue from 'vue/dist/vue.esm.js'
import RelationshipButton from '../components/RelationshipButton.vue'

document.addEventListener('DOMContentLoaded', () => {
  new Vue({
    el: '#relationship',
    components: { RelationshipButton },
  })
});

無事に表示されることができました!!
完全ビルド後.png

参考記事
Vue.jsの完全ビルドとランタイムビルドの違い
https://qiita.com/sansaisoba/items/58f8176f6e462fe4d591

<!--function (e,n,r,o){return sn(t,e,n,r,o,!0)}-->になった原因
https://stackoverflow.com/questions/49334815/vue-replaces-html-with-comment-when-compiling-with-webpack

0
0
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
0
0