LoginSignup
10
14

More than 3 years have passed since last update.

RailsにWebpackerでVue.jsを入れたら行う設定

Last updated at Posted at 2019-12-07

環境: Rails 5.2/6.0、Webpacker 4.2、Vue.js 2.6

コンパイラ入りのVue.jsを使う

.vueファイルの中のテンプレートではなく、Railsが出力したHTMLやtemplate:で指定したHTMLをテンプレートとして使う場合は、コンパイラ(HTMLパーサ)入りのビルドを使う必要があります。

コンパイラ入りビルドを使わないと、ブラウザーでの実行時にHTMLをパースできなくなり、次のエラーが出ます。

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

webpackの設定で、environment.config.resolve.aliasを次のように指定すると、import Vue from 'vue' でコンパイラ入りのvue/dist/vue.esm.jsが使えます。

config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const { VueLoaderPlugin } = require('vue-loader')
const vue = require('./loaders/vue')

environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())
environment.loaders.prepend('vue', vue)
// Vue.js フル版(Compiler入り)
environment.config.resolve.alias = { 'vue$': 'vue/dist/vue.esm.js' }
module.exports = environment

この指定がないときは、import Vue from 'vue' はコンパイラなしのvue/dist/vue.runtime.esm.jsになります。.vueファイルの中のテンプレートだけ使う場合はそれでかまいません。

IE11対策

詳しくは、Rails+WebpackerでのIE11対策をご覧ください。

application.jsに次の2行を入れると、IE11が対応していない新しめのJavaScriptの機能が使えるようになります。この2つはWebpackerを入れれば入るので、yarn addしなくても使えます。

app/javascript/packs/application.js
import "core-js";
import "regenerator-runtime/runtime";

Vue.jsはデフォルトでIE 11に対応しているので、Vue.jsの基本的な機能だけ使うならこの2つは要りません。IEが対応していないJavaScriptのメソッドや組み込みクラスを使うときは core-js、asyncとawaitを使うときは regenerator-runtime が必要です。

Turbolinks対策

Turbolinksを使っている場合はvue-turbolinksを入れないと、ブラウザーの戻るボタンなどで動作がおかしくなります。

$ yarn add vue-turbolinks
app/javascript/packs/application.js
import TurbolinksAdapter from 'vue-turbolinks';
Vue.use(TurbolinksAdapter);

jQueryとBootstrapを使う

Rails 6にjQueryとBootstrapを入れるで書きました。Webpackerで入れる方法と、assetsを使う方法があります。

AxiosでCSRF対策用のトークンを設定

Rails+AxiosでCSRF対策用のトークンを使う設定 で書きました。AxiosのInterceptorsの機能を呼び出すコードを書いて、実行しておきます。

10
14
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
10
14