Sage 10: Adding jQuery?

I’m wondering how to effectively make jQuery available to front-end scripts. With the following snippets I receive the following front end Javascript error… TypeError: $ is not a function

Here are the relevant code snippets I’ve tried.

/**
 * Register the theme assets.
 *
 * @return void
 */
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_script('jquery');
    bundle('app')->enqueue();
}, 100);

Is there any way to add jquery as a dependency to the bundle when enqueueing?

/**
 * @typedef {import('@roots/bud').Bud} bud
 *
 * @param {bud} app
 */
module.exports = async (app) => {
  app
    /**
     * Application entrypoints
     *
     * Paths are relative to your resources directory
     */
    .entry({
      app: ['@scripts/app', '@styles/app'],
      editor: ['@scripts/editor', '@styles/editor'],
      admin: ['@scripts/admin', '@styles/admin'],
    })

    .externals({
      jQuery: 'window.jquery',
    })

Is there anything else I’d need in the app.js file or elsewhere? Additionally is there any way to specify that I only need jQuery available for @scripts/app?

Much thanks for any help!

2 Likes

Solution could be in “provide”, but it is actually a bug : [bug] .provide() throws error in Sage 10 · Issue #1233 · roots/bud · GitHub

Documentation : bud.provide | bud.js

2 Likes

While the bug is addressed, you can use the extensions API directly.

bud.extensions.get("webpack-provide-plugin").setOption("$", "jquery")

To do both $ and jQuery you can use the extension controller’s setOptions method:

bud.extensions.get("webpack-provide-plugin").setOptions({
  $: "jquery",
  jQuery: "jquery",
})

There is a fix for this in 5.6.0 via improve: build, cache, compiler by kellymears · Pull Request #1229 · roots/bud · GitHub

1 Like

To confirm, this is fixed as of 5.6.0:

app.provide({
  jquery: ["jQuery", "$"],
})

:pray:t3:

7 Likes