What am I missing when writing jQuery in app.js?

When I write something simple in app.js like

$("#myID").removeClass("show");

I get an error in the console saying that: Uncaught TypeError: $ is not a function

I am writing it in // application code:

import {domReady} from '@roots/sage/client';

/**
 * app.main
 */
const main = async (err) => {
  if (err) {
    // handle hmr errors
    console.error(err);
  }

  // application code
  $("#myID").removeClass("show");
};

/**
 * Initialize
 *
 * @see https://webpack.js.org/api/hot-module-replacement
 */
domReady(main);
import.meta.webpackHot?.accept(main);

You need to enqueue jQuery.

For example add to functions.php

function frontend_scripts_and_styles() {

  if ( $GLOBALS['pagenow'] !== 'wp-login.php' && ! is_admin() ) {

    // Deregister WordPress jQuery
    wp_deregister_script( 'jquery' );
    // Load CDN
    wp_register_script( 'jquery', '//code.jquery.com/jquery-3.6.0.min.js', null, '3.6.0', false );
    wp_enqueue_script( 'jquery' );

  }
}

add_action( 'wp_enqueue_scripts', 'frontend_scripts_and_styles' );
1 Like

try const $ = jQuery;

Probably a Compatibility Mode issue: How To Properly Add jQuery Scripts To WordPress (Easy Steps) - WPMU DEV