LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】jQueryを使えるようにする(Webpacker)

Posted at

はじめに

この記事ではRailsでjqueryを使うための設定を説明します。
この記事の最後では実際にjqueryが使えているかどうかについて確認する仕方についても載せています

jQueryを導入する

まずは端末で以下のコマンドを打ちます

ターミナル
yarn add jquery

次にenvironment.jsの編集を行います

config/webpack/environment.js
const { environment } = require('@rails/webpacker')
// ↓ 追加
const webpack = require('webpack')
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery'
    })
)
//ここまで

module.exports = environment

次にapplication.jsの編集を行います

app/javascript/packs/application.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

Rails.start()
Turbolinks.start()
ActiveStorage.start()
// ↓追加
require('jquery')

ここまででjqueryのインストールは完了です
最後にちゃんと設定できているか確認します

jQueryのバージョン確認

まずはアプリを立ち上げます

ターミナル
$ rails s

※ここで注意なのですがすでにアプリを立ち上げている人は一度接続を切ってもう一度立ち上げてください

次にデベロッパーツールを開きコンソールでconsole.log($.fn.jquery)と打ちます

Q3k1N0OIMl7c4HR1617410622_1617410634.png

そしたら右下にjqueryのバージョンが出てくるとおもいますのでこれが出てきたらちゃんと設定できています
お疲れ様でした。

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