我在 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);
}
在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] 删除。
我来说两句