How to use JQueryUI in views in Rails 6

*爱你&永不变心* 提交于 2020-12-31 04:48:57

问题


I am having difficulty using JQuery and JQueryUI in a Rails 6 app.

JQuery and JqueryUI both work in application.js

HOWEVER, JQueryUI is not working in views. How do I make it work in both cases? My code is below.

I ran yarn add jquery

I ran yarn add jquery-ui-dist

In environment.js:

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

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

const aliasConfig = { 'jquery': 'jquery/src/jquery', 'jquery-ui': 'jquery-ui-dist/jquery-ui.js' };
environment.config.set('resolve.alias', aliasConfig);

module.exports = environment

In application.js:

require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
require("jquery-ui");
require("custom/scripts")

I test out JQuery and JQueryUI in a custom/scripts.js and in packs/search.js

custom/scripts.js is loaded in application.js and looks like this:

$(document).ready(function(){
  var test = $().jquery
  console.log('custom/scripts.js JQuery version ==> ' + test);

  var test_ui = $.ui ? $.ui.version || "pre 1.6" : 'jQuery-UI not detected';
  console.log('custom/scripts.js UI version ==> ' + test_ui);
});

packs/search.js is loaded in the view with

<%= javascript_pack_tag "search" %>

packs/search.js looks like this (exact same as custom/scripts.js):

$(document).ready(function(){
  var test = $().jquery
  console.log('packs/search.js JQuery version ==> ' + test);
  
  var test_ui = $.ui ? $.ui.version || "pre 1.6" : 'jQuery-UI not detected';
  console.log('packs/search.js UI version ==> ' + test_ui);
});

The result in the console:

custom/scripts.js JQuery version ==> 3.5.1
custom/scripts.js UI version ==> 1.12.1
packs/search.js JQuery version ==> 3.5.1
packs/search.js UI version ==> jQuery-UI not detected

回答1:


The problem is maybe how Webpack resolves the plugin. I have removed this line

 $: 'jquery'

in environment.js and seem likes it works!



来源:https://stackoverflow.com/questions/65131308/how-to-use-jqueryui-in-views-in-rails-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!