簡體   English   中英

如何將 JavaScript 庫導入 WordPress

[英]How to import a JavaScript Library into WordPress

我正在嘗試將“Rough Notation”JS 庫集成到我的 WordPress 網站中。

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

我只是在使用他們的基本演示代碼(位於: https ://glitch.com/~basic-rough-notation),它使用以下腳本:

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

(我將其作為 'annotate-text.js' 加載到 WordPress 中)

最初我收到以下錯誤:

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)

但是在閱讀了 StackOverflow 上的一些答案后,我設置了以下腳本來加載 RoughNotation 模塊:

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 );

所以,看起來它正在工作並且 RoughNotation 正在加載。 但現在我得到另一個不同的錯誤:

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

想知道是否有人可以告訴我如何解決這個問題。

我再次檢查了 StackOverflow,但不確定如何實現類似問題的答案。

謝謝

關於如何將 Javascript 庫添加到您的 Wordpress 網站有一個很棒的教程,請檢查以下內容: 如何將 Javascript 庫添加到 Wordpress 網站

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM