Rails 6 app install Glide.js using Yarn (webpacker) - Uncaught ReferenceError: Glide is not defined

Rails 6 app install Glide.js using Yarn (webpacker) - Uncaught ReferenceError: Glide is not defined

我真的很难应对 Rails 的所有新 JS 更改。我正在尝试实现非常简单的滑块脚本,Glide.js

这是我的 app/javascripts/packs/front.js 文件:

// Internal
// require("@rails/ujs")
import Glide from '@glidejs/glide'
console.log(Glide);

import Rails from '@rails/ujs'
Rails.start()
require('jquery')
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Custom

require('./vendor_js/vendor_import.js')

这是我在其中调用 gilder (new_slider.js) 的文件:

// require("./slider.js");
require("./new_slider.js");

require("./mBox.js");
require("./lightbox_script.js");
require("./map.js");
// import lightbox from "packs/custom/lightbox_script.js";

这是 new_slider.js 文件:

$(document).on('turbolinks:load', function(){
  console.log("new_slider.js is loaded");
  var slider = document.querySelector('.glide');

  if (slider) {
    var glide = new Glide(slider);
    console.log("glide is loaded:");
    console.log(glide);
    glide.mount();
  }

});

这是我的 haml 观点:

.glide
  .glide__track{"data-glide-el" => "track"}
    %ul.glide__slides
      %li.glide__slide
        %img{:src => asset_path('slider/winter_holidays/1.jpg'), :style => "width:100%"}/
      %li.glide__slide
        %img{:src => asset_path('slider/winter_holidays/2.jpg'), :style => "width:100%"}/
      %li.glide__slide
        %img{:src => asset_path('slider/winter_holidays/3.jpg'), :style => "width:100%"}/

  %div{"data-glide-el" => "controls"}
    %button{"data-glide-dir" => "<<"} start
    %button{"data-glide-dir" => ">>"} end

这是我的控制台输出:

ƒ Glide$() {
    classCallCheck(this, Glide$);
    return possibleConstructorReturn(this, (Glide$.__proto__ || Object.getPrototypeOf(Glide$)).apply(this, arguments));
  }
new_slider.js:2 new_slider.js is loaded
new_slider.js:6 Uncaught ReferenceError: Glide is not defined
    at HTMLDocument.<anonymous> (new_slider.js:6)
    at HTMLDocument.dispatch (event.js:328)
    at HTMLDocument.elemData.handle (event.js:148)
    at Object../node_modules/turbolinks/dist/turbolinks.js.e.dispatch (turbolinks.js:75)
    at r.notifyApplicationAfterPageLoad (turbolinks.js:994)
    at r.pageLoaded (turbolinks.js:948)
    at turbolinks.js:872

由于console.log(Glide) 提供了输出,Gilde 显然已加载。 new_slider.js 文件是在导入 Gilde 后加载的,所以不会有任何冲突。到目前为止我发现的唯一问题是 ,但不幸的是它根本没有帮助。

有人能给我指出正确的方向吗?

尝试加载 jquery 作为全局插件:

# config/webpack/environment.js

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

const webpack = require('webpack');

environment.plugins.append('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
)

module.exports = environment

然后从 application.js

中删除 require("jquery")

在 Webpack 领域,您通常需要在要使用它的每个文件中显式导入给定模块。所以,即使你在 app/javascripts/packs/front.js 中导入了 Glide,如果你想在 new_slider.js 中引用它,你也需要在那里导入它:

// new_slider.js
import Glide from '@glidejs/glide';

// ...