1
votes

Rails 6, Webpacker and Flickity

Quick demo app: https://github.com/ratahtatah/flickedyflack

Try 1: Pure jQuery

TypeError: $(...).flickity is not a function

app/javascript/packs/application.js

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

require("jquery")

require("flickity")
import "flickity/dist/flickity.min.css";

$(".main-carousel").flickity({
  contain: true
});

config/webpack/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',
    flickity: 'flickity/dist/flickity.pkgd.min'
  })
)

module.exports = environment

Try 2: jQuery w/ jQueryBridget (Feifei Xiong)

No errors, but also no initialization

app/javascript/packs/application.js

var $ = require('jquery');
var jQueryBridget = require('jquery-bridget');
var Flickity = require('flickity');

jQueryBridget('flickity', Flickity, $);

$(".main-carousel").flickity({
  contain: true
});

package.json

{
  "name": "flicketyflack",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "flickity": "^2.2.1",
    "jquery": "^3.4.1",
    "jquery-bridget": "^2.0.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}
2
Could you post your package.jsonFeifei Xiong
@FeifeiXiong all done :)Mark Boulder

2 Answers

1
votes

Maybe you need to use jquery-bridget to initialize Flickity as a jQuery plugin.

yarn add jquery-bridget

Then in application.js

var $ = require('jquery');
var jQueryBridget = require('jquery-bridget');
var Flickity = require('flickity');

jQueryBridget( 'flickity', Flickity, $ );

# If your are using turbolinks
$(document).on('turbolinks:load', function() {
  $(".main-carousel").flickity({
    contain: true
  });
});

If you are not using turbolinks, try following:

$(document).ready(function() {
  $(".main-carousel").flickity({
    contain: true
  });
});
0
votes

Try adding this line to your application.js

import $ from 'jquery';

Add it before $(".main-carousel").flickity...