Rails 6: How to add jquery-ui through webpacker?
Asked Answered
U

8

9

I'm currently trying to implement a datepicker into my application, the problem is that there is no documentation on how to add the jquery-ui-rails gem through webpacker.

Probably there is another way to add gems or another gem that would fit my needs?

Unfit answered 19/8, 2019 at 11:19 Comment(2)
Don't use gems to just add javascript libraries, use yarn to handle javascript dependencies and install jquery-ui using this yarnpkg.com/en/package/webpack-jquery-ui.Modal
Tried installing jquery-ui using yarn but that doesn't make it available to other javascript files. I think it needs to be added as a plugin within webpack, similar to jQuery, but I couldn't get that to work so I'm currently using sprockets for jquery and jquery-ui until I can get a satisfactory solution using yarn/webpack.Riparian
T
24

You no longer need to add javascript libraries as gems (which are managed by the bundler). Instead, you add them with yarn and they are managed by webpack (which is enabled by adding the webpacker gem to the Gemfile).

The following steps worked for me to get jquery-ui working in Rails 6:

  1. On the terminal, inside your application type:
yarn add jquery-ui-dist
  1. Your config/webpack/environment.js needs to look as follows:
const { environment } = require('@rails/webpacker')

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

const aliasConfig = {
    'jquery': 'jquery-ui-dist/external/jquery/jquery.js',
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
};

environment.config.set('resolve.alias', aliasConfig);

module.exports = environment
  1. Restart your rails server

  2. In the application.html.erb, include the jquery-ui theme:

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery UI Test</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

    <%= stylesheet_link_tag '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/le-frog/jquery-ui.min.css' %>

    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>
  1. Now, in your app/javascript/packs/application.js, you can use jquery-ui:

NOTE: If you would like to use jQuery inside your views folder, make it available globally

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

// THIS IS MAKING jQuery AVAILABLE EVEN INSIDE Views FOLDER
global.$ = require("jquery")

require("jquery") // Don't really need to require this...
require("jquery-ui")

$(function(){
    // Plain jquery
    $('#fadeMe').fadeOut(5000);

    // jquery-ui
    const availableCities = ['Baltimore', 'New York'];
    $('#cityField').autocomplete( { source: availableCities } );
    $('#calendarField').datepicker( { dateFormat: 'yy-mm-dd' } );
})

This will work for a page that looks as follows:

<div id='fadeMe'>I will fade</div>

City: <input type='text' id='cityField' />
Calendar: <input type='text' id='calendarField' />
Triiodomethane answered 27/10, 2019 at 14:48 Comment(11)
Just wanna point out, for newbies, that you need to restart your rails server after updating your config/webpack/environment.js, or else this will not work. This answer worked and has helped me fix the issue with jquery ui. Working on a Rails 6 app here. Thumbs up for the greatly detailed answer too!Glyptodont
Thanks @RicardoGreen - I have updated my answer with your suggestionTriiodomethane
jQuery.ui still returns undefined for mePoland
For me works when I changed aliasConfig : const aliasConfig = { 'jquery': 'jquery/src/jquery', 'jquery-ui': 'jquery-ui-dist/jquery-ui.js' };Jeep
You are my hero. I was struggling with this issue for like 3 hours. Couldn't redefine the jquery-ui.Drupelet
Haha - glad my answer helped you! :)Triiodomethane
This doesn't work for me when I include autocomplete in a view. For example, if you put autocomplete in a pack/search.js and then call <%= javascript_pack_tag 'search' %> in the view, then autocomplete does not work.Alfi
I posted a question about the issue I found trying to use this answer as a solution here: #65131808Alfi
@Alfi - you see how in step 5 above I have global.$ = require("jquery") I think this is what makes jQuery available inside the views. Maybe if you do something similar with jQuery UI (as in global.jQueryUI = require("jquery-ui") ) and then check if jQueryUi is available as a global var in your view???Triiodomethane
@Triiodomethane I thought so too, but I don't know how to set it up. I tried global.jQueryUI = require("jquery-ui") but that doesn't work.Alfi
How to include the css from jquery-ui-dist folder?. You have loaded the css externally. Great answer but the same thing can be done for the javascript as well.Silberman
S
7

None of these answers quite worked for me. Here's how I ended up getting it implemented:

yarn add jquery

then

yarn add jquery-ui-dist

in your app/javascript/packs/application.js file:

// jquery
import $ from 'jquery';

global.$ = $
global.jQuery = $


require('jquery-ui');

// jquery-ui theme
require.context('file-loader?name=[path][name].[ext]&context=node_modules/jquery-ui-dist!jquery-ui-dist', true,    /jquery-ui\.css/ );
require.context('file-loader?name=[path][name].[ext]&context=node_modules/jquery-ui-dist!jquery-ui-dist', true,    /jquery-ui\.theme\.css/ );

and in config/webpack/environment.js:

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

const webpack = require('webpack');


// resolve-url-loader must be used before sass-loader
environment.loaders.get('sass').use.splice(-1, 0, {
    loader: 'resolve-url-loader',
    options: {
        attempts: 1
    }
});


// Add an additional plugin of your choosing : ProvidePlugin

environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
        $: 'jquery',
        JQuery: 'jquery',
        jquery: 'jquery',
        'window.Tether': "tether",
        Popper: ['popper.js', 'default'], // for Bootstrap 4
    })
)

const aliasConfig = {
    'jquery': 'jquery/src/jquery',
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'

};

environment.config.set('resolve.alias', aliasConfig);

//
module.exports = environment;

A restart to my server got it working fine for me. Here is a link with details on webpacker that I used to get this to work:

https://gist.github.com/maxivak/2612fa987b9f9ed7cb53a88fcba247b3#jquery-jquery-ui

Stoa answered 27/12, 2019 at 1:20 Comment(3)
Is anyone getting the following issue? CssSyntaxError: /Users/username/Project/my_rails_app/jquery-ui.css:1:1: Unknown wordVally
this works actually except ...... for some reason when I load it only via application.js pack the jQuery.ui object is undefined (Except jQuery is defined), but this is fixed if if I add require("jquery-ui-dist/jquery-ui"); to the pack that I'm working in on my page (which, incidentally, is loaded as its own pack via javascript_pack_tag in the Rails layout)Poland
if I add require("jquery-ui-dist/jquery-ui"); to the pack (in addition to application.js), then jQuery.ui is available both within that module and also globally at the debugging console — not sure why this effect is this wayPoland
S
4
$ yarn add webpack-jquery-ui

and in application.js

require('webpack-jquery-ui');
require('webpack-jquery-ui/css');

did the job for me. (I had setup jquery before which might need some additional config)

Weblink: https://www.npmjs.com/package/webpack-jquery-ui

(This is the same process as in Tushar Patil's answer yet with another package).

Soma answered 29/5, 2020 at 10:52 Comment(0)
P
4

Kalman's answer worked for me, although not from the very beginning (I'm writing it in a separate answer as I don't have enough reputation to comment on the original answer yet :) )

So, beware that when you put require("jquery-ui") in app/javascript/packs/application.js, the functions provided by jquery-ui will not be available in your scripts loaded to individual views with javascript_pack_tag

The reason for that is that these individual scripts will load before application.js loads.

To make it work, I had to put require("jquery-ui") in one of these individual scripts that depended on jquery-ui

BTW, it works in Kalman's example, as he wrote his script directly in application.js, after requiring "jquery-ui"

Perreault answered 14/12, 2020 at 12:42 Comment(0)
A
0

Kalman's answer puts jQuery within the scope of the scripts in the app/javascript directory but not with any in-line javascript that you may have on your webpages.

If you want to access jQuery from the scope of the webpage, you could can put jQuery under the public directory then modify app/views/layouts/application.html.erb to link to it like this:

<!DOCTYPE html>
<html>
  <head>
    <title>JqueryTest</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>


    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <script src="/jquery-3.4.1.js"></script>
    <%= stylesheet_link_tag "/jquery-ui-1.12.1.custom/jquery-ui.min.css" %>
    <script src="/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>


  </head>

  <body>
    <%= yield %>
  </body>
</html>

Abrade answered 28/10, 2019 at 18:5 Comment(2)
I think this defeats the purpose of Webpacker and ES6+ import/exportPoland
also with this you can confuse yourself with conflicting or different versions of jQuery — one loaded from webpacker and the other loaded from your public/ directoryPoland
Q
0

Above steps works fine, removed extra steps

The following steps worked for me to get jquery-ui working in Rails 6:

1) On the terminal, inside your application type:
yarn add jquery-ui-dist

2) in app/javascript/packs/application.js
require("jquery-ui-dist/jquery-ui");

3) In the application.html.erb, include the jquery-ui theme

<%= stylesheet_link_tag '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/le-frog/jquery-ui.min.css' %>

4) restart the rails server and webpack dev server.

Quirinus answered 29/3, 2020 at 15:28 Comment(2)
something is missing jquery.ui is not loaded for mePoland
still getting jQuery.ui as undefinedPoland
F
0

For me a hybrid of several articles, and things worked and looked the most elegant

CLI:

    yarn add jquery jquery-ui-dist

app/javascript/packs/application.js:

// ... SNIP ...
require("jquery")
require("jquery-ui")

config/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'
  })
)

const aliasConfig = {
    'jquery': 'jquery/src/jquery',
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'

};

environment.config.set('resolve.alias', aliasConfig);

module.exports = environment

app/views/layouts/application.html.erb

<%= stylesheet_link_tag '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' %>
Fomentation answered 13/9, 2020 at 23:15 Comment(0)
K
0
  1. Run on the terminal (CLI)

yarn add jquery jquery-ui-dist

  1. Add to the config/webpack/environment.js
...

const webpack = require("webpack")
environment.plugins.append("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);
...
  1. app/javascript/packs/application.js:

require("jquery-ui")

  1. For the theme add code to any scss file. Do change according to your nee.
.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;   
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px; }

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none; }

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none; }
Karlise answered 28/9, 2020 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.