首页 > 解决方案 > 如何在 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 文件在模块之后排队,并且所有文件都正确加载。有什么想法我哪里出错了吗?

标签: javascriptwordpress

解决方案


type="module"在错误的文件上添加了。我需要在要使用该功能的文件上添加模块类型。


推荐阅读