How to use fancybox with webpack?

Jaditpol picture Jaditpol · Oct 25, 2017 · Viewed 8.9k times · Source

I'm currently developing a webpage and started using webpack in my build process. I've managed to use slick-carrousel plugin downloaded via npm but can't make fancybox to work!

I've downloaded it via npm and imported it as stated in the documentation:

var $ = require("jquery");
var slick = require("slick-carousel");
var fancybox = require("fancybox")($);

Then in my code I try to initailize a fancybox object and nothing happens. It throws no errors at all.

$(".filtros__filtrar").on('click', function() {    
  $.fancybox.open({
    src  : '#tns-filtros',
    type : 'inline',
    opts : {
      smallBtn: false
    }
  });
});

If I do a console log of those variables I get:

console.log(fancybox);  ->  undefined
console.log(slick);     ->  {}

Which means slick module is loading correctly but not fancybox.

Somewhere I read that you have to use imports-loader to make fancybox recognize jquery variables. So I downloaded it via npm and included this in my webpack.config file:

module: {
  rules: [
    {
      test: /fancybox[\/\\]dist[\/\\]js[\/\\]jquery.fancybox.cjs.js/,
      use: "imports-loader?jQuery=jquery,$=jquery,this=>window"
    }
  ]
}

But it doesn't work either.

Can someone give me a light on this subject? Thanks in advance!

Answer

Jaditpol picture Jaditpol · Oct 28, 2017

Ok. I managed to solve the problem like this.

First, I realized that I installed Fancybox 2 instead of Fancybox 3 so I uninstalled the first and installed the last (Thanks to @Mikhail Shabrikov for making me realize that!).

npm uninstall fancybox --save-dev
npm install @fancyapps/fancybox --save

Second, I dig through Fancybox original code and saw that it requires jQuery to be passed to it as window.jQuery and not $ so in my requires I did this:

var $ = require("jquery");
window.jQuery = $;  <-- This is what do the magic!!
var slick = require("slick-carousel");
require("@fancyapps/fancybox");

And voila! Everything works now.