Webpack引入Justified-Gallery报$(...).is not a function错误如何解决
问题成因
- jQuery插件依赖全局jQuery实例挂载方法:Justified Gallery属于传统jQuery插件,加载时会自动将自身方法挂载到
$.fn(jQuery原型链)上,要求运行环境中存在全局可访问的jQuery/$对象。如果webpack打包时jQuery仅作为模块局部变量存在,没有暴露到全局,或者插件和你业务代码中使用的jQuery不是同一个实例,就会出现$(...).justifiedGallery is not a function的错误。 - ES6 Import提升导致加载顺序错乱:你入口文件中
import './js/init.js'虽然写在require('justifiedGallery')之后,但ES6的import语法会被JavaScript引擎预解析,执行优先级远高于CommonJS的require,导致你的业务代码先执行、插件后加载,自然无法调用还没挂载的方法。 - 引入方式不符合插件逻辑:你尝试的将
justifiedGallery直接挂载到window的写法没用,这类jQuery插件不需要暴露到全局window,只需要挂载到jQuery原型链上即可,这种写法完全不符合插件的设计逻辑,自然无效。 - 可能存在包名引入错误:npm官方发布的Justified Gallery包名为
justified-gallery(小写加横杠),如果你的引入语句写的是驼峰格式的justifiedGallery,可能根本没有正确加载到插件代码。
解决方法
1. 配置webpack将jQuery暴露到全局
修改Rails项目的config/webpack/environment.js,用ProvidePlugin统一注入jQuery实例:
const { environment } = require('@rails/webpacker') const webpack = require('webpack') // 统一所有模块的jQuery引用,同时挂载到window environment.plugins.append('Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }) ) module.exports = environment
2. 修正入口文件的引入顺序和写法
将所有依赖的引入都统一用import语法,避免加载顺序错乱,同时修正包名:
// 引入样式文件 import 'lightgallery/scss/lightgallery-bundle' import 'justified-gallery/dist/css/justifiedGallery.min.css' // 引入基础库 import lightGallery from 'lightgallery' import lgThumbnail from 'lightgallery/plugins/thumbnail' import lgZoom from 'lightgallery/plugins/zoom' // 引入jQuery插件,引入后会自动挂载到$.fn import 'justified-gallery' // 全局暴露需要的方法 window.lgZoom = lgZoom window.lgThumbnail = lgThumbnail window.lightGallery = lightGallery // 最后引入业务代码 import './js/init.js';
3. 确认依赖安装正确
如果上述操作后仍报错,可以先重装依赖确认包存在:
yarn add jquery justified-gallery
内容的提问来源于stack exchange,提问作者Roberto Pezzali
相关产品推荐
相关产品推荐

