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