[wp-trac] [WordPress Trac] #56313: wp_enqueue_script needs to be able to handle modules (ES6/ES2020)

WordPress Trac noreply at wordpress.org
Sun Jul 31 08:33:35 UTC 2022


#56313: wp_enqueue_script needs to be able to handle modules (ES6/ES2020)
---------------------------+------------------------------
 Reporter:  idad5          |       Owner:  (none)
     Type:  enhancement    |      Status:  new
 Priority:  normal         |   Milestone:  Awaiting Review
Component:  Script Loader  |     Version:
 Severity:  normal         |  Resolution:
 Keywords:  2nd-opinion    |     Focuses:  javascript
---------------------------+------------------------------
Changes (by costdev):

 * keywords:   => 2nd-opinion
 * focuses:   => javascript
 * severity:  major => normal


Comment:

 Hi @idad5, welcome back to Trac!

 I think it makes sense that this is in Core territory rather than a third-
 party plugin. This ''should'' be reasonably straightforward. - it can even
 just be done through filters:

 {{{#!php
 <?php
 // In Core, functions.php or a plugin:
 add_filter( 'script_loader_tag', 'slug_add_module_support', 999, 2 );
 function slug_add_module_support( $tag, $handle ) {
         if ( str_contains( $handle, 'nomodule' ) ) {
                 return str_replace( '<script', '<script nomodule', $tag );
         }

         if ( str_contains( $handle, 'module' ) ) {
                 if ( current_theme_supports( 'html5', 'script' ) ) {
                         return str_replace( '<script', '<script
 type="module"', $tag );
                 } else {
                         return str_replace( 'text/javascript', 'module',
 $tag );
                 }
         }

         return $tag;
 }

 // Then when a developer needs to enqueue module and nomodule scripts:
 add_filter( 'wp_enqueue_scripts', 'slug_enqueue_scripts' );
 function slug_enqueue_scripts() {
         $modules = array(
                 'module-say-hello' => '/js/say-hello.js',
                 'module-app'       => '/js/app.js',
                 'nomodule-app'     => '/js/app.nomodule.js',
         );

         foreach ( $modules as $handle => $src ) {
                 wp_enqueue_script( "slug-$handle",
 get_template_directory_uri() . $src );
         }
 }
 }}}

 {{{#!js
 // say-hello.js
 export const sayHello = () => console.log('hello')

 // app.js
 import { sayHello } from './say-hello.js'
 sayHello()

 // app.nomodule.js
 function sayHello() {
         console.log('hello')
 }
 sayHello()
 }}}

 For now, I'll add the `2nd-opinion` keyword to get some thoughts on the
 enhancement from other contributors.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/56313#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list