$ is not defined when installing jQuery in Rails via Webpack

后端 未结 5 1432
猫巷女王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: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 
    

提交回复
热议问题