简体   繁体   English

在 Webpacker 中使用 jQuery 插件

[英]Use jQuery plugins in Webpacker

I have a Rails 5 application with Webpacker.我有一个带有 Webpacker 的 Rails 5 应用程序。

I am trying to add Infinite scroll using its jQuery plugin but I keep getting:我正在尝试使用其 jQuery 插件添加无限滚动,但我不断收到:

cars.js:20 Uncaught TypeError: $(...).infiniteScroll is not a function car.js:20 Uncaught TypeError: $(...).infiniteScroll 不是函数

My cars.js file looks like:我的 cars.js 文件如下所示:

import 'infinite-scroll'

$('.item').infiniteScroll({
      path: `.paginator--cars .next_page a`,
      append: `.car`,
      scrollThreshold: false,
      status: '.page-load-status',
      button: '.view-more-cars-button',
      history: 'push'
    });

My application.js file looks like:我的 application.js 文件看起来像:

import 'jquery/src/jquery'
import '../js/cars'

My environment.js file looks like:我的 environment.js 文件看起来像:

const { environment } = require('@rails/webpacker')

module.exports = environment

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

Any ideas?有任何想法吗? This is bugging me so much?这让我很烦?

Neil尼尔

In this case, you don't need jQuery.在这种情况下,您不需要 jQuery。

Yes, when using this package in the browser, it makes itself available as a jQuery plugin ( source ).是的,当在浏览器中使用这个包时,它可以作为一个 jQuery 插件( 源代码)使用。

But, when accessed via Node.js, such as when bundled in Webpack, jQuery is not necessary;但是,当通过 Node.js 访问时,例如捆绑在 Webpack 中时,不需要 jQuery; this package makes itself available as an AMD or CommonJS export ( source ).这个包本身可以作为 AMD 或 CommonJS 导出( )。

A quick glance at the project indicates the proper usage for you in your cars.js file would be instead:快速浏览一下这个项目,你就会发现在你的cars.js文件中的正确用法是:

import InfiniteScroll from 'infinite-scroll'

new InfiniteScroll('.item', {
  // options
})

I'd also assume wrapping the new InifiteScroll(...) expression in a window.addEventListener('DOMContentLoaded', () => {}) callback would make sense as well.我还假设将new InifiteScroll(...)表达式包装在window.addEventListener('DOMContentLoaded', () => {})回调中也是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM