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
  • 2
  • 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

1 Answers1

0

You need to ensure that main.js is loaded as an ES6 Module to do this. First add a filter to the script_loader_tag hook;

add_filter( 'script_loader_tag', 'load_as_ES6',10,3 );

It will call this function that appends the type "module" to the script tag.

public function load_as_ES6($tag, $handle, $source){
        if('main'===$handle){
            $tag ='<script src="' . $source . '" type="module" ></script>';
        }
        return $tag;
    }

main.js will then be recognised an ES6 module that can import the exports of other ES6 modules by writing something like this at the top of the file:

import { countUp } from 'path_to_module/countUp.min.js'