javascript - 如何在 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"
在错误的文件上添加了。我需要在要使用该功能的文件上添加模块类型。
推荐阅读
- sql - PL/SQL 程序显示顶级“a”员工的薪水
- asp.net-mvc - JQuery Ajax Post - 操作返回部分视图但未成功或显示
- .net - 在 .NET Core 中添加 Content-Type JSON 标头
- java - Apache Camel data types between components
- python - numpy中的多维累积和
- ios - 如何使用 ARKit 或 Apple Vision 测量 3d 对象的尺寸?
- c++ - 避免只在源文件中定义的类的弱 vtable 警告
- c# - 在类“程序”上调用方法“BuildWebHost”时发生错误。在没有应用程序服务提供者的情况下继续 - ASP.NET CORE 迁移
- azure - 您可以删除 Microsoft.Web/certificates 吗?
- angular - 如何在 Angular 2 中为单元测试创建新事件?