Search code examples
webpackphotoswipe

Webpack require other libraries


I am trying to get my assets working with a webpack configuration.

I have split all my JS from one large .js file into separate ones with a main application.js file that requires them all.

Now one of these files:- gallery.js needs the PhotoSwipe library. I have it installed in my node_modules directory and at the top of gallery.js I have:

require('photoswipe/dist/photoswipe.min');
require('photoswipe/dist/photoswipe-ui-default.min');

But when running the page, in the console I get:

gallery.js?a942:77 Uncaught ReferenceError: PhotoSwipe is not defined
    at openPhotoSwipe (gallery.js?a942:77)
    at HTMLAnchorElement.eval (gallery.js?a942:89)
    at HTMLAnchorElement.dispatch (vendor.js:5530)
    at HTMLAnchorElement.elemData.handle (vendor.js:5338)

Can anyone point me in the direction of where I am going wrong so I can fix the undefinedness of PhotoSwipe?

Thanks, Neil


Solution

  • You can do two things to get this work.

    1. Assign the required libraries into variable and use that wherever needed like,

      var PhotoSwipe = require('photoswipe');
      var PhotoSwipeUIDefault = require('photoswipe/dist/photoswipe-ui-default');
      
    2. Use ProvidePlugin to populate the PhotoSwipe variable for you like,

      plugins: [
         new webpack.ProvidePlugin({
            PhotoSwipe: 'photoswipe',
            PhotoSwipeUI_Default: 'photoswipe/src/js/ui/photoswipe-ui-default.js'
        })
      ]