且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 6:如何通过webpacker添加jquery-ui?

更新时间:2023-02-21 09:48:51

您不再需要将JavaScript库添加为gem(由捆绑器管理).取而代之的是,您将它们添加到yarn中,并由webpack(通过将webpacker gem添加到Gemfile中启用)来管理它们.

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).

以下步骤对我有用,以使jquery-ui在Rails 6中正常工作:

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

  1. 在终端上,在您的应用程序中键入:

yarn add jquery-ui-dist

  1. 您的config/webpack/environment.js需要看起来如下:
  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. application.html.erb中,包含jquery-ui主题:
  1. 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. 现在,在您的app/javascript/packs/application.js中,您可以使用jquery-ui:
  1. Now, in your app/javascript/packs/application.js, you can use jquery-ui:

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

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'>Fade me</div>

City: <input type='text' id='cityField' />
Calendar: <input type='text' id='calendarField' />