Cannot link third-party library to a js script in Sage theme WordPress

688 views Asked by At

I have installed a third-party library called Moment.js through bower install --save moment. I have a script named calendar.js placed in scripts folder of my theme. However, when I use moment in my calendar.js it seems the library isn't linked to it. When I move all the code from calendar.js to main.js, everything works fine. The problem is that I need to pass the data into the script by loading a json file and send the data by AJAX so I need to make a separate script, which, in this case, calendar.js. So how do I solve this problem?

Edit: I've enqueued calendar.js in my theme's functions.php like this:

function igs_scripts_styles() {
  wp_enqueue_script( 'calendar', get_template_directory_uri() . '/assets/scripts/calendar.js', array(), false, true );
}
add_action('wp_enqueue_scripts', 'igs_scripts_styles');
2

There are 2 answers

0
fatg On

It's not really a solution to this problem but a workaround. So I noticed when I moved all the code from calendar.js to main.js it worked all fine. What I did is enqueuing calendar.js with the dependency of main.js (because moment.js is available in main.js). Here's the code:

 wp_enqueue_script( 'calendar', get_template_directory_uri() . '/assets/scripts/calendar.js', ['sage/js'], null, true );
6
Johny Santiago On

You need to register and enqueue script before using it in wordpress then only wordpress will be able to recognise the script. As of what i can understand the main.js and Moment.js scripts are added properly using wp_enqueue_script which is why they are working fine. I believe if you enqueue the Calendar.js as well that JS file will work fine too.