Lint
Lint

Reputation: 935

WordPress JavaScript import error Cannot use import statement outside a module

Before posting a new question, I already explored the existing question on Stack Overflow but unfortunately they didn't work.

So I'm getting the Uncaught SyntaxError: Cannot use import statement outside a module error, the question that I reviewed tell to use type=module in script tag or use any Babel tool etc.

But the main thing is I'm using this in my WordPress project and for the reason above methods doesn't work in my case. Here is my file in which I'm trying to import jquery but getting the import error.

import $ from 'jquery';
class Search {
    constructor() {
            console.log('Custom constructor called');
            this.openButton = $(".js-searh-trigger");
            this.closeButton = $(".js-search-overlay__close");
            this.searchOverlay = $(".search-overlay");
            this.events();
        }
        // 2. Evetns
    events() {
            this.openButton.on('click', this.openOverlay)
            this.closeButton.on('click', this.closeOverlay)
        }
        // 3. Methods
    openOverlay() {
        this.searchOverlay.addClass('search-overlay--active')
    }
    closeOverlay() {
        this.searchOverlay.removeClass('search-overlay--active')
    }
}
export default Search;
alert('search js working')
console.log(
    'custom working'
)

Upvotes: 0

Views: 1369

Answers (1)

Nate G
Nate G

Reputation: 132

Do you mean that you're using it on the client side? In that case, you should load jQuery using a script tag, rather than use import. E.g:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Upvotes: 1

Related Questions