簡體   English   中英

嘗試在我的 Wordpress PHP 文件中將幾個 Javascript 腳本排入隊列后,如何防止“無法在模塊外使用導入語句?”

[英]After trying to enqueue several Javascript scripts in my Wordpress PHP file, how can I prevent “cannot use import statement outside a module?”

I'm writing a plugin for my Wordpress php file, which seeks to emulate an HTML file I had previously made, which calls several Javascript in this manner:

<script src="./Controller/myfile.js" type="module" defer></script>

但是,對於 Wordpress,我沒有制作簡單的.html 文件,我不能直接這樣做。 我已將腳本排入隊列,但是當我嘗試將 go 運行到這些腳本的運行位置時,我看到Uncaught SyntaxError: Cannot use import statement outside a module and unexpected token: export in the browser console。 我需要在 my.php 文件中添加什么來解決此問題?

文件./Controller/myfile.js或您在 WP 中排隊的任何其他文件必須是您的 JS 的最終輸出/構建。 這意味着您不能有import語句或類似的東西,因為所有代碼都必須在該文件中。 這是因為一旦 WP 在<script>中呈現您的文件,就不會發生進一步的處理(即沒有解析模塊,etc。)。 我建議使用Gulpjs 之類的東西來捆綁您的源 js 代碼並生成一個縮小的構建文件,然后您可以將其排入隊列。

編輯:

如果您的入隊腳本沒有type="module" ,請按照上面 Aioros 的評論並使用 module 作為您的 type 屬性將其正確入隊。 我仍然建議使用捆綁包,因為 type="module" 對developer.mozilla.org 模塊type="module" has limited support

當您使用wp_enqueue_script()將腳本排入隊列時,您最終會得到如下腳本元素:

<script src="./Controller/myfile.js"></script>

如您所見,它沒有type="module"屬性,我想這就是您收到import錯誤的原因。 有幾種方法可以添加它。

我不知道您究竟是如何注冊/排隊腳本,但讓我們假設它是這樣的:

wp_enqueue_script("myfile", "Controller/myfile.js");

然后你可以在你的插件中添加一個過濾器,比如:

function add_type_module_attribute($tag, $handle) {
   if ( $handle !== 'myfile' ) {
      return $tag;
   }
   // needed in case you already have a type='javascript' attribute
   $new_tag = str_replace("type='text/javascript'", '', $tag);
   // adding type='module'
   $new_tag = str_replace(" src", " type='module' defer src", $tag);
   return $new_tag;
}
add_filter('script_loader_tag', 'add_type_module_attribute', 10, 2);

暫無
暫無

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

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