简体   繁体   中英

How to import a JavaScript Library into WordPress

I'm trying to integrate the 'Rough Notation' JS Library into my WordPress website.

See: https://roughnotation.com/ https://github.com/rough-stuff/rough-notation

I'm just using their basic demo code (at: https://glitch.com/~basic-rough-notation ) which uses the following script:

<script type="module">
  import { annotate } from 'https://unpkg.com/rough-notation?module';
  
  const n1 = document.querySelector('em');
  const n2 = document.querySelector('strong');
  const n3 = document.querySelector('h1');
  const n4 = document.querySelector('span');
  const n5 = document.querySelector('#block');
  
  const a1 = annotate(n1, { type: 'underline', color: 'blue' });
  const a2 = annotate(n2, { type: 'circle', color: 'red', padding: 10 });
  const a3 = annotate(n3, { type: 'box', color: 'orange' });
  const a4 = annotate(n4, { type: 'highlight', color: 'yellow', iterations: 1, multiline: true });
  const a5 = annotate(n5, { type: 'bracket', color: 'red', padding: [2, 10], brackets: ['left', 'right'], strokeWidth: 3 })
  
  a1.show();
  a2.show();
  a3.show();
  a4.show();
  a5.show();
  
</script>

(I'm loading this into WordPress as 'annotate-text.js')

Initially I got the following error:

annotate-text.js?ver=6.0.1:1 Uncaught SyntaxError: Cannot use import statement outside a module (at annotate-text.js?ver=6.0.1:1:1)

but after reading through some answers on StackOverflow I set up the following script to load the RoughNotation module:

function annotate_scripts() 
   wp_enqueue_script( 'module_handle', get_stylesheet_directory_uri() . '/js/annotate-text.js', 
   array(), false, true );

}

add_action( 'wp_enqueue_scripts', 'annotate_scripts' );


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

So, it looks like it's working and RoughNotation is loading. But now I get another, different error:

Uncaught TypeError: Cannot read properties of null (reading 'parentElement')
at p.attach (rough-notation.esm.js?module:1:9287)
at new p (rough-notation.esm.js?module:1:8501)
at _ (rough-notation.esm.js?module:1:12411)
at annotate-text.js?ver=6.0.1:10:18

Wondering if someone can show me how to resolve this.

I've checked through StackOverflow again but not sure how to implement answers to similar problems.

Thanks

关于如何将 Javascript 库添加到您的 Wordpress 网站有一个很棒的教程,请检查以下内容: 如何将 Javascript 库添加到 Wordpress 网站

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM