繁体   English   中英

如何在 WordPress 环境中导入 ES6 风格的模块?

[英]How to import ES6 style modules in a WordPress environment?

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

我收到一个错误:未捕获的语法错误Uncaught SyntaxError: import declarations may only appear at top level of a module顶层。

问题概要:

我想在其他文件(如product.js文件)中使用我的helpers.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 function,我尝试像这样导入它:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM