Patrik CK
Patrik CK

Reputation: 25

jQuery not loading into custom js file in WordPress

I'm writing a bit of code in a custom js file located in /mytheme/js/live-search.js At the top of the js file I have [ import $ from 'jquery'; ]. In my functions.php i have my wp_enqueue_script function with the dependency of array('jquery'), but I still get an Uncaught SyntaxError: Unexpected identifier for the first line in that js file when I load the page.

I have this same setup on a local WP site I'm working on and it's working just fine there. What am I missing?

in functions.php

function asset_files() {
    wp_enqueue_script('search-jsfile', get_theme_file_uri('/js/live-search.js'), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'asset_files');

This is the begining of my code

class Search {
    constructor() {
        this.openButton = $("#search-icon-btn");
        this.closebutton = $(".search-overlay__close");
        this.searchOverlay = $(".search-overlay");
        this.events();
    }

    events() {
        this.openButton.on("click", this.openOverlay);
        this.closebutton.on("click", this.closeOverlay);
    }

    openOverlay() {
        this.searchOverlay.addClass("search-overlay--active");
    }

    closeOverlay() {
        this.searchOverlay.removeClass("search-overlay--active");
    }
}

var liveSearch = new Search();

Upvotes: 0

Views: 350

Answers (1)

Andrew Savetchuk
Andrew Savetchuk

Reputation: 1610

jQuery is part of WordPress core. You don't need to import it twice.

Just remove import $ from 'jquery'; in your live-search.js file.


Also, the import statement is a part of ES6 features.

To make ES6 modules work in browsers you should add type="module" to script tag like so:

<script type="module" src="filename.js"></script>

Upvotes: 1

Related Questions