简体   繁体   中英

Rails 6: Include 3rd Party Yarn Library via Webpacker

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? eg I only need it on gallery.html.erb

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

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