使用 type="module" 将 javascript 入队

lop*_*dpe 13 javascript wordpress es6-modules

我想countUp.js在 Wordpress 中使用我的自定义主题。

当我添加文件时wp_enqueue_script(),出现错误:

Uncaught SyntaxError: Unexpected token 'export'
Run Code Online (Sandbox Code Playgroud)

我读过它可以在<script>label上进行固定设置type="module",但我不知道该怎么做,因为该选项不存在于wp_enqueue_script()...

任何人都可以帮助我吗?

Pau*_*eda 25

可以通过应用过滤器“ script_loader_tag ”向脚本添加属性。

使用add_filter('script_loader_tag', 'add_type_attribute' , 10, 3);添加的过滤器。

像上面链接中给出的示例一样定义回调函数:

function add_type_attribute($tag, $handle, $src) {
    // if not your script, do nothing and return original $tag
    if ( 'your-script-handle' !== $handle ) {
        return $tag;
    }
    // change the script tag by adding type="module" and return it.
    $tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
    return $tag;
}
Run Code Online (Sandbox Code Playgroud)

  • @AviG 是的,你知道。您可以首先使用 `wp_enqueue_script( 'your-script-handle', 'script-file.js' );` 将脚本排入队列,然后使用 `add_filter('script_loader_tag', 'add_type_attribute' , 10, 3); 添加过滤器` (4认同)