更新时间: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:
yarn add jquery-ui-dist
config/webpack/environment.js
需要看起来如下: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
application.html.erb
中,包含jquery-ui
主题: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>
app/javascript/packs/application.js
中,您可以使用jquery-ui
: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' />