Как использовать jqueryUI в альфа-движке rails 6 или rails 7

Я был бы признателен, если бы кто-нибудь смог показать точные шаги, необходимые для использования jquery ui в движке rails 6 или rails 7 Alpha 2. Мне не удалось заставить ни importmap-rails работать в движке rails 7, ни заставить webpacker работать в движке Rails 6 или rails 7 alpha 2. Учитывая движок custom_page, созданный с использованием

      rails plugin new custom_page --mountable --full

Я включил jquery-ui-rails в gemspec в качестве зависимости.

      spec.add_dependency 'jquery-ui-rails'

Возможно, это должна быть runtime_dependency? Полный список зависимостей

        spec.add_dependency "rails", "~> 7.0.0.alpha2"

  spec.add_dependency 'new_ckeditor'

  spec.add_dependency 'ancestry'
  spec.add_dependency 'friendly_id', '>= 5.4.0'
  spec.add_dependency 'pg_search'

  spec.add_dependency 'carrierwave', '~> 2.0'
  spec.add_dependency 'carrierwave-imageoptimizer'
  spec.add_dependency 'sassc-rails', '~> 2.0.0'
  spec.add_dependency 'pg', '~> 1.1'
  spec.add_dependency 'jquery-rails'
  spec.add_dependency 'jquery-ui-rails'

  spec.add_development_dependency "puma"

  #Testing Gems
  spec.add_development_dependency "rspec-rails", '>= 5.0'
  spec.add_development_dependency "factory_bot_rails"
  spec.add_development_dependency "guard-rspec"

  spec.add_development_dependency 'capybara', '>= 3.32'
  spec.add_development_dependency 'selenium-webdriver'
  spec.add_development_dependency 'launchy'
  spec.add_development_dependency 'database_cleaner-active_record'

Я потребовал то же самое в engine.rb

      require 'jquery-ui-rails'
require 'friendly_id'
require 'ancestry'

    module CustomPage
      class Engine < ::Rails::Engine
        isolate_namespace CustomPage
    
        config.generators do |g|
          g.test_framework :rspec,
            fixtures: false,
            request: false,
            view_specs: false,
            helper_specs: false,
            controller_specs: false,
            routing_specs: false
          g.fixture_replacement :factory_bot
          g.factory_bot dir: 'spec/factories'
        end
      end
    end

Я добавил простой тест в представление

      <p id="notice"><%= notice %></p>

<script type='text/javascript'>
  $(function() {
    $('.datepicker').datepicker();
  });
</script>

Я включил требование в app/assets/stylesheets/custom_page/application.css

      /*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
 /*
  *= require jquery-ui
 */

А также в app / assets / config / custom_page_manifest.js

      //= link_directory ../stylesheets/custom_page .css
//= require jquery-ui

Я получаю сообщение об ошибке при проверке консоли браузера в firefox, показывающей

      Uncaught ReferenceError: $ is not defined

Я, очевидно, показал здесь пример Rails 7 alpha 2, однако та же проблема возникает при использовании rails 6.1.4.

Цель этого упражнения - дать мне возможность использовать библиотеку jquery jqtree, которую было бы просто настроить, если бы я мог использовать importmap-rails, однако, согласно моему открытому, пока еще не ответившему вопросу, здесь я не могу сделать так.

Итак, я действительно спрашиваю, как использовать библиотеки jquery в движках Rails 6.1.4 или в библиотеках Rails 7 alpha 2

1 ответ

Это было не так просто, как я думал. Прежде всего, и кажутся устаревшими. Я не думаю, что вы должны использовать эти драгоценные камни. Мы можем использовать importmaps, так как мы уже настроили его для движка. Но использование не ограничивается двигателем.

      # config/importmap.rb

# NOTE: pin jquery to jsdelivr. this will make jquery global on import;
#       jspm wraps packages in a module [1], so jquery is not available globally.
pin "jquery", to: "https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.js"

# NOTE: a few answers suggested `jquery-ui-dist`. I couldn't add it with 
#       `bin/importmap`; use https://generator.jspm.io/ to get the url.
pin "jquery-ui-dist", to: "https://ga.jspm.io/npm:jquery-ui-dist@1.13.1/jquery-ui.js"

# works fine
pin "jqtree", to: "https://ga.jspm.io/npm:jqtree@1.6.2/lib/tree.jquery.js"

# [1] someone, please, link to/explain what jspm does exactly to cause this.
      // app/javascript/application.js

import "jquery";
import "jquery-ui-dist";
import "jqtree";

console.log(window.$);   // jQuery is already global
console.log($.ui);       // jquery-ui initialized on import
console.log($().tree);   // jqtree also initialized

Если вы по какой-то причине хотите придерживаться jspm, динамический import()может использоваться для загрузки плагинов jquery.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports

      # config/importmap.rb

pin "jquery", to: "https://ga.jspm.io/npm:jquery@3.6.0/dist/jquery.js"
pin "jquery-ui-dist", to: "https://ga.jspm.io/npm:jquery-ui-dist@1.13.1/jquery-ui.js"
pin "jqtree", to: "https://ga.jspm.io/npm:jqtree@1.6.2/lib/tree.jquery.js"
      // app/javascript/application.js

import jQuery from "jquery";

// NOTE: keep in mind, these will be lazily loaded; use first method if this 
//       doesn't work in your set up.
import("jquery-ui-dist");
import("jqtree");

console.log(window.$);      // undefined
console.log(window.jQuery); // undefined
console.log(jQuery().ui);   // undefined
console.log(jQuery().tree); // undefined

// NOTE: make jquery global
window.$ = window.jQuery = jQuery;

Для установки rails 6 с jquery-ui-railsа также jquery-railsдрагоценные камни. Убедитесь, что вам также требуется jquery. Не трогайте manifest.js , вы не компилируете jquery, вы предварительно компилируете application.{css,js}, который уже включает jquery. Вы должны добавить requireтакже в application.js .

https://github.com/rails/jquery-rails#installation

https://github.com/jquery-ui-rails/jquery-ui-rails#require-все

      // app/assets/javascripts/application.js

//= require jquery
//= require jquery-ui
      /* app/assets/stylesheets/application.css */

/*= require jquery-ui */
Другие вопросы по тегам