When I first introduced jQuery for the first time in programming, I said, "Install jQuery with gem. The js file is read by changing" pack-tag "to" inculude-tag "using the asset pipeline." learned. After that, from rails6, webpacker (gem that introduces webpack) is installed as standard, and I heard that introduction in the asset pipeline is not common, so I wanted to introduce jQuery with webpacker.
ruby 2.6.5 rails 6.0.3.2
Create an application and move it to the application you created in the terminal. Also start the local server.
Type the following command in the terminal:
terminal
$ yarn add jquery
Add the code to the contents of the file as shown below.
config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
})
)
module.exports = environment
Add the following code.
app/javascript/packs/application.js
require('jquery')
Create a test.js file and load it.
app/javascript/packs/application.js
require('../test')
app/javascript/test.js
$(function(){
alert('jQuery is installed.')
});
If the jQuery load is successful, "jQuery is installed." Will be displayed in the alert. If it fails, "$" cannot be used and an error is displayed on the console.
Recommended Posts