RailsアプリへのjQueryの導入方法

概要

RailsアプリにjQueryを導入する方法の覚書です。

目次

  • jQueryのインストール
  • webpackの設定
  • jqueryの読み込み

jQueryのインストール

jQueryのインストールはyarnを用いて行います。

元々はjquery-railsというgemが利用されていましたが、Rails6から変更になっています。

ターミナル

yarn add jQuery

webpackの設定

config/webpack/environment.jsを編集します。

 

const { environment } = require('@rails/webpacker')

// jquery導入部分
const webpack = require("webpack")
environment.plugins.prepend("Provide",
  new webpack.ProvidePlugin({
    $: "jquery/src/jquery",
    jQuery: "jquery/src/jquery"
  })
)
// jquery導入部分終わり

module.exports = environment

 

jqueryの読み込み処理

最後にapplication.jsを編集してjQueryを読み込めるようにします。

// 追加

require("jquery")