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

后端 未结 8 945
失恋的感觉
失恋的感觉 2021-01-05 04:12

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

8条回答
  •  执念已碎
    2021-01-05 04:31

    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:

    
    
      
        Jquery UI Test
        <%= 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' %>
      
    
      
        <%= yield %>
      
    
    
    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:

    I will fade
    City: Calendar:

提交回复
热议问题