Cannot initialize PhotoSwipe
I am trying to initialize my gallery, but it throws these errors:
Uncaught TypeError: Cannot set property 'PhotoSwipeUI_Default' of undefined Uncaught TypeError: Cannot set property 'PhotoSwipe' of undefined Uncaught ReferenceError: PhotoSwipe is not defined
I imported the scripts like this:
<script src="assets/js/photoswipe-ui-default.js"></script> <script src="assets/js/photoswipe.js"></script>
And here is my init code for the gallery.
const pwspElement = document.querySelector('.pswp'),
items = [/Items here/],
options = {index: 0},
gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options)
gallery.init()
According to the Chrome console, the problem is on this line in photoswipe.js:
root.PhotoSwipe = factory();
UPDATE:
Linking the the 2 JS scripts with script tag in HTML as below works, but when I want to concatenate the files with my JS with Gulp, I get the above error.
<script src='https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.js'/>
<script src='https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.min.js'/>
Try adding if(root === undefined && window !== undefined) root = window; right after (function (root, factory) {
Having the same problem. My workaround was to add this to my gulp task:
var replace = require('gulp-replace');
gulp.src(...).pipe(replace(/(root\.PhotoSwipe(UI_Default)? = factory\(\);)/g, "root=window;$1"))
@groe see https://github.com/bebraw/libumd and https://github.com/search?o=desc&q=gulp+umd&s=stars&type=Repositories&utf8=%E2%9C%93
Thanks for the hint @DanielRuf!
I'm using Gulp with Babel. Having the same problem.
I switched Babel from Modules mode to Scripts mode by adding { modules: false } to @babel/env preset options. Now Babel isn't transpiling this into void 0 here:
/**
* before transpiling (modules mode)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.PhotoSwipeUI_Default = factory();
}
})(this, function () {
/**
* after transpiling (modules mode)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.PhotoSwipeUI_Default = factory();
}
})(void 0, function () {
Here's a simplified chunk from my Gulpfile:
gulp
.src(...)
.pipe(
babel({
presets: [['@babel/env', { modules: false }], '@babel/react']
})
)
.pipe(gulp.dest(...))
Read this SO answer for the explanation.
Hope that helps somebody.
Try adding
if(root === undefined && window !== undefined) root = window;right after(function (root, factory) {
This seems to work for me 👍
However using babel-loader for webpack 4 I needed to also change my import to
import * as PhotoSwipeUI_Default from '~/path-to-photoswipe.js to deal with a missing default export
{ modules: false }
@vanokhin Worked perfectly. Thanks!