7
3

More than 3 years have passed since last update.

[Rails6 / jQuery導入] Uncaught TypeError: $ is not a function のエラー解決

Last updated at Posted at 2020-08-23

開発環境

Ruby 5.2.1
Rails 6.0.3.2

はじめに

rails 5の頃はgemを使ってjQueryをインストールしていましたが、
rails 6からはWebpackerを用いてjQueryをインストールするようになりました。

Rails6でjQueryの導入方法
Introducing jQuery in Rails 6 Using Webpacker

このあたりの記事を参考に導入していきましたが、このようなエラーが…。
スクリーンショット 2020-08-23 8.42.07.png
Uncaught TypeError: $ is not a function
どうやら 「$」が機能していないみたい。

ちなみにjsファイルにconsole.log('test'); だけ入力すると、
このようにjavascriptが動作しているため、jsファイルを読み込めていない系の
トラブルでは無いことがわかる。
スクリーンショット 2020-08-23 13.03.45.png

解決方法

結論:webpackの環境ファイルを修正して、解決しました

修正前

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

修正後

config/webpack/environment.js
const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery',        # 修正完了     
        jQuery: 'jquery/src/jquery'
    })
)
module.exports = environment

最後に

これでrails6環境でjsが使える!

ブログに今回実施したjQuery導入手順をまとめたので、よかったら見てください。

nakauの技術ブログ 〜プログラミングを学ぶ〜
Rails6 - jQuery導入方法
7
3
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
7
3