我真的很难处理JS对Rails的所有新更改。我正在尝试实现愚蠢的简单滑块脚本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();
}
});
这是我的观点:
.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$$1() {
classCallCheck(this, Glide$$1);
return possibleConstructorReturn(this, (Glide$$1.__proto__ || Object.getPrototypeOf(Glide$$1)).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
Gilde显然是加载的,因为console.log(Glide(提供了一个输出。new_slider.js
文件是在导入Gilde
之后加载的,因此不会有任何冲突。到目前为止,我发现的唯一问题是这个问题,但不幸的是,它根本没有帮助。
有人能给我指正确的方向吗?
在Webpack领域,您通常需要在每个要使用的文件中显式导入给定的模块。因此,即使您在app/javascripts/packs/front.js
中导入了Glide
,如果您想在new_slider.js
中引用它,也需要在那里导入:
// new_slider.js
import Glide from '@glidejs/glide';
// ...
尝试将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")