The Rails apps I've made so far
--Sprockets + JS library read from layout file with CDN --Webpacker + JS library loaded with npm
I had only made this pattern, but this time
--Sprockets + JS library loaded with npm
I will make an application called, and I will make a note of how to do it.
Specifically, I will introduce the process of introducing the library https://swiperjs.com/
.
npm itself comes with downloading node.js
. Since node.js should have been installed when building the Rails environment,
$ npm -v
When the version is displayed with, it is OK.
Install the library you want to install with npm.
$ npm install swiper
Starting with npm version 4, it will update package.json
without the --save
option.
Add the path to the asset pipeline while looking at the path under node_modules
. In the case of swiper
this time, the necessary fileswiper-bundle.js
was in the following location.
node_modules
└── swiper
└── swiper-bundle.js
So, in application.js
, enter as follows.
assets/javascripts/application.js
//= require rails-ujs
//= require activestorage
//= require swiper/swiper-bundle.js #Postscript
//= require_tree .
If you have the code required for initialization, create another file in assets/javascripts
or write it in application.js
. This time I wrote it in application.js
.
assets/javascripts/application.js
$(function() {
new Swiper('.swiper-container', {
loop: true,
// If we need pagination
pagination: {
el: '.swiper-pagination',
},
// Navigation arrows
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
})
})
Now, swiper
works safely ^^
It was fun to look back on the recent trends of Rails and JS ^^ The following is an article that I referred to.
-Asset Pipeline-Rails Guide --Install the front-end library used by Rails from npm -Rails 6: Fully understand Webpacker + Yarn + Sprockets and write JavaScript: Part 1 (translation)
Recommended Posts