Rails 6: Include 3rd Party Yarn Library via Webpacker

Viewed 735

I added jQuery to Webpack and it seems to work.

I tried to add a JS Library called "Swiper", but I just don't get how to include it.

Here is what I did:

yarn add swiper (success)

environment.js:

const { environment } = require('@rails/webpacker')

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

module.exports = environment

application.js:

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

import 'Swiper';

In my Console I'm getting:

Uncaught Error: Cannot find module 'Swiper'

Uncaught ReferenceError: Swiper is not defined

Bonus question: How could I even include the Swiper JS on only a specific view? e.g. I only need it on gallery.html.erb

1 Answers

In your application.js:

import Swiper from 'swiper'
window.Swiper = Swiper

I don't think it's necessary to put it in your environment.js

Related