React js 18 - Considerations for jQuery with Rails and Webpack
We have a few options for how we include jQuery and a few considerations:
Considerations
- jquery-ujs 13 monkey patches $.ajax to send the CSRF parameters. For more info on this, see: Rails Guides on CSRF 13. This is the key file that gets inserted: rails.js 5. This code uses the jQuery.ajaxPrefilter 4 from this line 6. If this file is not loaded in the Rails
application.js
, then the CSRF token is not added when when$.ajax
(or it’s friends, like$.get
) is called. This is part of the jquery-rails gem 21. Note, there is no separate gem forjquery-ujs
. However, there’s a separate github repo, probably so that it can be used by npm, but I’m just guessing. - We under NO CIRCUMSTANCES want to load 2 versions of jQuery. We want the version of jQuery used to be as transparent as possible. Is the reason obvious? Thus, it’s critical that we load jQuery from the gem, then we DO NOT load jquery in the webpack config.
- It turns out that there is a npm version of jquery-ujs 31!
#Options for jQuery Inclusion
A. jQuery loaded from Rails
Having jQuery included before loading the bundle from web, and specify jQuery as an “external” 43.
1. jquery-rails Gem
Use the jquery-rails gem 21 and be sure to specify what version of jQuery. This is somewhat obtuse, as it requires locking the jQuery version by the gem version. This is specified here 16.
2. jQuery from a CDN
Use the jquery-rails-cdn 10 gem. If we do that, we need to load it first in the Rails main application layout. This gem will use this version of jQuery:
jQuery version is automatically detected via jquery-rails
B. jquery-ujs and jquery from npm
Let’s load both jquery-ujs and jquery in our webpack configuration. The advantages to doing this:
-
It’s clear what versions we’re using as they specified just like the other dependencies. This is the way we’re handling all other 3rd party JavaScript, so let’s be consistent.
-
No chance of accidentally having a different version loaded from both Rails and Webpack.
-
We simply need to expose jQuery as global so that other JavaScript or CoffeeScript code in the Rails project that’s not using the Webpack config can find
jQuery
and$
. This is documented for Webpack 27: -
We need to expose the jquery-ujs part, through an addition to the entries so this gets loaded by webpack (PENDING EXAMPLE).
-
You need to use the expose-loader.
npm install expose-loader --save
You can either do this when you require it:
require("expose?$!jquery");
or you can do this in your config:
loaders: [
{ test: /jquery\.js$/, loader: 'expose?$' },
{ test: /jquery\.js$/, loader: 'expose?jQuery' }
]
We will very shortly have this as an example here: https://github.com/shakacode/react-webpack-rails-tutorial/issues/51 92.
Questions
- How useful is the CDN for jQuery performance wise?