Hotwire Turbo in WordPress

214 Views Asked by At

I wish to use Hotwire Turbo in my WP app.

I'm including it like so:

wp_enqueue_script('Turbo', 'https://unpkg.com/@hotwired/[email protected]/dist/turbo.es2017-esm.js', array(), '7.3.0', false);

The above line is inside a function that gets called below:

add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

and ensuring it's getting treated as a module with:

function set_scripts_type_attribute( $tag, $handle, $src ) {
    if ( 'Turbo' === $handle ) {
        $tag = '<script type="module" src="'. $src .'"></script>';
    }
    return $tag;
}

But i'm getting this error:

application.js:29 Uncaught ReferenceError: Turbo is not defined at application.js:29:1

Anyone have any idea how to resolve this?

Thanks

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

1

There are 1 best solutions below

0
borisano On

Seems that you are not setting any dependencies for the script. This means that the script will not be able to find the other JavaScript files that it needs.

To fix this error, you need to add the following dependency to the wp_enqueue_script() call:

wp_enqueue_script('Turbo', 'https://unpkg.com/@hotwired/[email protected]/dist/turbo.es2017-esm.js', array('jquery'), '7.3.0', false);

The jquery dependency is required by the Turbo script. Once you have added this dependency, the error should go away.

Here is the complete code that you need to load the Turbo script in WordPress:

function enqueue_scripts() {
    wp_enqueue_script('Turbo', 'https://unpkg.com/@hotwired/[email protected]/dist/turbo.es2017-esm.js', array('jquery'), '7.3.0', false);
}

add_action('wp_enqueue_scripts', 'enqueue_scripts');