0

I want to add a js file that exports a class to my WordPress theme. But on using wp_enqueue_script() function, it shows

Uncaught SyntaxError: Unexpected token 'export'

How can I add the js module so that the export and import of class work properly?

This is my functions.php file. Here countUp.min.js exports a class and main.js import that class and use it for some functionalities. But I'm unable to export and import.

function loadJS(){
    wp_register_script('fontawesome', 'https://kit.fontawesome.com/486392b9f0.js', '','', true);
    wp_enqueue_script('fontawesome');
    wp_register_script('countUp', get_template_directory_uri().'/js/countUp.min.js', '', 1, true);
    wp_enqueue_script('countUp');
    wp_register_script('showOnScroll', get_template_directory_uri().'/js/show-on-scroll.js', '', 1, true);
    wp_enqueue_script('showOnScroll');
    wp_register_script('products', get_template_directory_uri().'/js/products.js', '', 1, true);
    wp_enqueue_script('products');
    wp_register_script('main', get_template_directory_uri().'/js/main.js', array('countUp'), 1, true);
    wp_enqueue_script('main');
}
add_action('wp_enqueue_scripts', 'loadJS');

In main.js file, the import statement is

import { CountUp } from './countUp.min.js';

The error I got is

Uncaught SyntaxError: Cannot use import statement outside a module
dchhitarka
  • 21
  • 1
  • 7
  • Hi Deepak, can you give a little more detail? Perhaps even show some of the code you're using to call wp_enqueue_script()? – craigmj Mar 13 '20 at 09:28
  • I have added the code from functions.php in the question – dchhitarka Mar 13 '20 at 09:34
  • 2
    These scripts would need to be embedded with `type="module"` set on the `script` element, see https://stackoverflow.com/a/58679392/1427878 But WordPress probably does not currently have this implemented, so you might need to hook into the `script_loader_tag` filter and fix the generated HTML in this regard, for the affected script resources. – CBroe Mar 13 '20 at 09:53
  • Thank you @CBroe, it's working properly now! – dchhitarka Mar 13 '20 at 10:07

0 Answers0