Development environment
table of contents
__1. Introduce jquery with yarn add jquery __ __2. Write a description to add jQuery under management to environment.js in the webpack configuration file __ __3. Write a description to call jQuery in application.js __ __4. Check if the javascript call is described in application.html.erb __
Terminal
$ yarn init *Note: I don't think it is necessary if you have already installed yarn on your OS with Homebrew.
$ yarn add jquery
__ * Supplement: __ I have no problem with just "yarn add jquery", but when I checked the articles of other people, there was an explanation that "yarn init" should be entered first, so I wrote it as a supplement. Let me do it. For "Install yarn with Homebrew", the article here will be helpful.
__ * Supplement 2: __ There is also a way to write gem'jquery-rails' in the Gemfile, but Rails 6 seems to recommend yarn add. This time, we are using the Node.js package to manage it with Webpacker.
2. environment.js
app/config/webpack/environment.js
//Copy and paste this description (the original description can be deleted)
//This is the description for adding jQuery under management in the webpack configuration file.
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
})
)
module.exports = environment
3. application.js
app/javascript/packs/application.js
//abridgement
require("@rails/ujs").start()
require("turbolinks").start() //I always comment out
require("@rails/activestorage").start()
require("channels")
require('jquery') //Add this
//abridgement
__ * Note: __turbolinks actively use the cache, so events that occur after the page is loaded may not work. I'm aware that it's a bit tricky to use javascript, so comment it out. (If you use the cache, the page load time will be shortened.)
html.erb:app/view/layouts/application.html.erb
<!--This is what happens when you remove tourbolinks-->
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_pack_tag 'application' %>
This is the flow up to the introduction of Jquery.
If $ is not defined, it means that jQuery has not been inserted properly, so I think that it can be solved by checking the 4 steps explained in the introduction of jQuery.
__1. Introduce jquery with yarn add jquery __ __2. Write a description to add jQuery under management to environment.js in the webpack configuration file __ __3. Write a description to call jQuery in application.js __ __4. Check if the javascript call is described in application.html.erb __
that's all.
Recommended Posts