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

arnasklas picture arnasklas · Aug 19, 2019 · Viewed 9.4k times · Source

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?

Answer

Kalman picture Kalman · Oct 27, 2019

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' />