$ is not defined when installing jQuery in Rails via Webpack

后端 未结 5 1451
猫巷女王i
猫巷女王i 2021-02-18 19:04

I\'m trying to install jQuery in Rails 6.0.0.rc1 via Webpack and I\'m not sure what I\'m missing but I\'m getting the error $ is not defined in the browser console

相关标签:
5条回答
  • 2021-02-18 19:15

    I tried a lot of things and some worked and some didn't, and some didn't work in my Docker container. In the end I settled on putting this in app/javascript/packs/application.js:

    global.$ = require('jquery')
    

    You need to do yarn add jquery of course.

    I'm sure there are better ways but this is the only thing that worked for me so I'm putting it up here in case it helps anyone else.

    0 讨论(0)
  • 2021-02-18 19:18

    i was trying to upgrade from rails 4 to rails 6. After few hours of debugging , finally i fixed this jQuery loading error.

    So here are the steps, I followed :

    1. add jQuery
    yarn add jquery 
    
    1. add expose-loader
    yarn add expose-loader  
    
    1. update config/webpack/environment.js file
    const { environment } = require('@rails/webpacker')
    
    environment.loaders.append('jquery', {
        test: require.resolve('jquery'),
        use: [{
            loader: 'expose-loader',
            options: '$',
        }, {
            loader: 'expose-loader',
            options: 'jQuery',
        }],
    });
    
    module.exports = environment
    
    
    1. update app/javascript/packs/application.js file
    require("@rails/ujs").start()
    require("turbolinks").start()
    require("@rails/activestorage").start()
    require("channels")
    
    require("jquery");
    
    1. restart webpack-dev-server
    bin/webpack-dev-server 
    

    Always restart webpack-dev-server, if you update environment.js file.

    if you want to use older version of jQuery (Ex: version 2.1.4 )

     yarn add jquery@2.1.4 
    
    0 讨论(0)
  • 2021-02-18 19:24

    The code in config/webpack/environment.js should look like this:

    environment.plugins.prepend('Provide',
      new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery'
      })
    )
    

    see also https://www.botreetechnologies.com/blog/introducing-jquery-in-rails-6-using-webpacker

    0 讨论(0)
  • 2021-02-18 19:31

    I've got what's missing.

    In app/javascript/packs/application.js forgot to declare:

    window.jQuery = $;
    window.$ = $;
    

    So jQuery keywords could be picked up.

    0 讨论(0)
  • 2021-02-18 19:39

    This solution worked for me with Rails 6.0.2.2 and yarn 1.16.0 https://stackoverflow.com/a/54906972/2970582

    0 讨论(0)
提交回复
热议问题