首页 > 解决方案 > 未捕获的类型错误:$(...)。当我使用 Webpack 导入库时不是函数

问题描述

我正在尝试在我的包中导入一个库,并且我尝试了各种方式,但每次我遇到错误。

该图书馆是Justified-Gallery,但有时其他图书馆也会发生这种情况,我必须了解问题出在哪里。

我正在使用带有 Rails 的 webpacker。

这是我的入口点,并且lightGallery,我正在使用的另一个库正在运行。

import 'lightgallery/scss/lightgallery-bundle'

// init vendor
import lightGallery from 'lightgallery'
import lgThumbnail from 'lightgallery/plugins/thumbnail'
import lgZoom from 'lightgallery/plugins/zoom'

window.lgZoom = lgZoom
window.lgThumbnail = lgThumbnail
window.lightGallery = lightGallery
require('justifiedGallery')


// init global user javascript
import './js/init.js';

Init.js 是我的主要脚本

import NavbarSingleTon, { Navbar } from './navbar';
import GallerySingleTon, { Gallery } from './gallery';

(function init() {
  document.addEventListener('DOMContentLoaded', () => {
    Navbar.init();
    Gallery.init();
  });
}());

最后这是我的gallery.js

export class Gallery {
  constructor($el) {
    $el.justifiedGallery({
      captions: false,
      lastRow: "hide",
      rowHeight: 180,
      margins: 5
    })
    .on("jg.complete", function () {
      window.lightGallery(
        document.getElementById("dmove_gallery"),
        {
          autoplayFirstVideo: false,
          pager: false,
          galleryId: "dmove",
          plugins: [lgZoom, lgThumbnail],
          mobileSettings: {
            controls: false,
            showCloseIcon: false,
            download: false,
            rotate: false
          }
        }
      );
    });
  }

  static init() {
    $(".gallery-container").each((i, el) => new Gallery($(el)));
  }
}

我在控制台中的错误是

gallery.js:5 Uncaught TypeError: $(...).justifiedGallery is not a function

我试图理解为什么,并且require('justifiedGallery')需要这个脚本

我尝试

import justifiedGallery from 'justifiedGallery'
window.justifiedGallery = justifiedGallery

但是什么都没有......我无法解决这个问题

标签: javascriptwebpack

解决方案


推荐阅读