如何在 WordPress 环境中导入 ES6 样式模块?

萨克德利克

我在 WordPress 环境中使用模块卡住了。请注意,这是我第一次使用模块,我只是想清理我的代码并在我的公司网站上进行组织。

我收到一个错误:Uncaught SyntaxError: import declarations may only appear at top level of a module使用 FireFox。

问题概要:

我想helpers.js在其他文件(如文件)中使用我的文件中的函数product.js我正在使用 WordPress 将它们排入队列。

入队文件:

我有一个functions.php将模块脚本type="module"排入队列的product.js文件,然后附加然后将我的文件排入队列

if (is_product()) {

   // Helper JS Module:
   wp_enqueue_script('helper-js', get_template_directory_uri() . '/js/helpers.js', array('product-js'), $theme_version, true);

   //Imports Helpers.js as a module:
   add_filter('script_loader_tag', 'add_type_to_script', 10, 3);
   function add_type_to_script($tag, $handle, $source) {
       if ('helper-js' === $handle) {
           $tag = '<script src="' . $source . '" type="module" ></script>';
       }
       return $tag;
   }

   // Main Product JS
   wp_enqueue_script('product-js', get_template_directory_uri() . '/js/product.js', array(), $theme_version, true);
}

ES6 模块:

helpers.js

const removeThisOption = (selectBox, optValue) => {
  for (var i = 0; i < selectBox.length; ++i) {
    if (selectBox.options[i].value === optValue) {
      selectBox.classList.remove("validated");
      selectBox[i].remove();
    }
  }
};

export { removeThisOption };

主要产品文件:

最后,我想removeThisOption在其他文件中使用上面函数,我尝试像这样导入它:

import { removeThisOption } from "./helpers.js";

但是,我仍然收到错误消息。product.js 文件在模块之后排队,并且所有文件都正确加载。任何想法我哪里出错了?

萨克德利克

type="module"在错误的文件中添加了我需要在我想在其中使用该函数的文件上添加模块类型。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章