繁体   English   中英

Rails 6 Webpacker:尝试安装 jQuery 和 JS 库

[英]Rails 6 Webpacker: Attempting to install jQuery and JS library

Rails 6、Webpacker 和Flickity

快速演示应用: https : //github.com/ratahtatah/flickedyflack

尝试 1:纯 jQuery

TypeError: $(...).flickity is not a function

应用程序/javascript/packs/application.js

require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")

require("jquery")

require("flickity")
import "flickity/dist/flickity.min.css";

$(".main-carousel").flickity({
  contain: true
});

配置/webpack/environment.js

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

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

module.exports = environment

尝试 2:jQuery w/ jQueryBridget (Feifei Xiong)

No errors, but also no initialization

应用程序/javascript/packs/application.js

var $ = require('jquery');
var jQueryBridget = require('jquery-bridget');
var Flickity = require('flickity');

jQueryBridget('flickity', Flickity, $);

$(".main-carousel").flickity({
  contain: true
});

包.json

{
  "name": "flicketyflack",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "flickity": "^2.2.1",
    "jquery": "^3.4.1",
    "jquery-bridget": "^2.0.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}

也许您需要使用 jquery-bridget 将 Flickity 初始化为 jQuery 插件。

yarn add jquery-bridget

然后在 application.js

var $ = require('jquery');
var jQueryBridget = require('jquery-bridget');
var Flickity = require('flickity');

jQueryBridget( 'flickity', Flickity, $ );

# If your are using turbolinks
$(document).on('turbolinks:load', function() {
  $(".main-carousel").flickity({
    contain: true
  });
});

如果您没有使用 turbolinks,请尝试以下操作:

$(document).ready(function() {
  $(".main-carousel").flickity({
    contain: true
  });
});

尝试将此行添加到您的 application.js

import $ from 'jquery';

$(".main-carousel").flickity...之前添加它$(".main-carousel").flickity...

①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

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

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