How Does Sage 9 Enqueue jQuery?

I’m trying to wrap my head around how Sage 9 enqueues jQuery… I read in a previous thread that Sage “tricks” WP into thinking that jQuery is enqueued?

I see the enqueue script in setup.php and the import'jquery' in the main.js file, but jQuery is also listed as a dependency in package.json. How does the import work, and where does it import from? How does the WP version get enqueued, or does it? Does Sage enqueue both the Wordpress jQuery and compile the node version into main.js, loading it twice?

How is everything tied together exactly, and how does that change if Soil is enabled?

Thanks!

That was in the old Roots theme

Sage does nothing special with jQuery, it simply lists it as a dependency for the main.js file that’s enqueued

The Sage main.js file is not built with jQuery included, you can see how by digging into the build config

Soil just loads jQuery from the jQuery CDN with a local fallback

The import in main.js automatically enqueues jQuery? If so, I’m not seeing how.

The jQuery dependency listed in package.json is never used?

Sorry, I’m super noob at this and not understanding…

No, the enqueue for main.js has jQuery as a dependency. This is normal for WordPress development. Look up how wp_enqueue_script works.

Right, I see how main.js is using ['jQuery'] as a dependency, but I’m still not understanding where and/or how jQuery is getting enqueued.

WordPress Core registers jQuery as an available library, so when you define it as a dependency it’s automatically enqueued. See the official documentation.

5 Likes

Thanks, alwaysblank! I didn’t realize that defining jQuery as a dependency on another script would automatically enqueue it. That makes sense!

Any comment on how the import'jquery' works in the main.js?

In Sage’s webpack configuration, jQuery is included under externals.

Per webpack’s documentation:

The externals configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer’s environment.

In other words, webpack is told to not bundle up jQuery, but import 'jquery' in main.js makes the jquery object/variable available to other things in main.js.

6 Likes

If jQuery is being enqueued by WP, and is also not bundled, is the import even necessary? Does it ever get used? And if it does, does it import from node_modules?

Good questions, but what have you tried so far to try and find the answers? Have you looked at any sort of documentation? This isn’t specific to Sage, so there are resources out there to help you wrap your head around these things

1 Like

Touche! I have not looked at the webpack documentation yet, nor have I ever used webpack, but it’s next on the agenda to learn. Onward…

Thanks, benword, alwaysblank!

1 Like