简体   繁体   中英

How do I use jQuery in Rails 6.0.3.3?

running Rails 6.0.3.3 and can't get jQuery to work.

Here's packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

And in my view I have something like this:

<head>
<%= javascript_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> 
</head>

 <div id="pop">
   TEST
 </div>
 <script>
    $(document).ready(function() { 
        $('#pop').hide(); 
      });
 </script>

And so when my page loads I would expect the #pop div that says 'TEST' to NOT show. It seems as if this set up is just not working. Thoughts?

Rails 6 doesn't include JQuery by default. It looks like you didn't install it.

Here's a link that shows how does Webpack works and how to install JQuery with Rails 6.

But if just want to install JQuery, here is how to do it:

Run yarn add jquery in your project.

Be sure to check if Jquery has been successfully installed by checking your package.json and yarn.json where the JQuery package should be visible.

Then add this snippet in your environment.js :

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

Your environment.js should then look like this:

const { environment } = require("@rails/webpacker");
const webpack = require("webpack");

environment.plugins.append(
  "Provide",
  new webpack.ProvidePlugin({
    $: "jquery/src/jquery",
    jQuery: "jquery/src/jquery",
  })
);

module.exports = environment;

Now simply add require('jquery') in your application.js .

application.js file:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM