Javascript 在WordPress插件中导入节点模块
我正在使用Javascript 在WordPress插件中导入节点模块,javascript,php,node.js,wordpress,Javascript,Php,Node.js,Wordpress,我正在使用wp\u register\u script和wp\u enqueue\u script为我正在开发的WordPress插件的管理屏幕引入一些自定义JavaScript逻辑 当我试图在JavaScript顶部添加import语句以引入两个节点模块时,问题就出现了。可以理解,这给了我以下浏览器控制台消息: 导入声明只能出现在模块的顶层 告诉WordPress将自定义JavaScript作为模块处理的标准方法是什么?为了确保可以导入节点模块,我还需要执行其他步骤吗?您可以尝试从unpkg加
wp\u register\u script
和wp\u enqueue\u script
为我正在开发的WordPress插件的管理屏幕引入一些自定义JavaScript逻辑
当我试图在JavaScript顶部添加import
语句以引入两个节点模块时,问题就出现了。可以理解,这给了我以下浏览器控制台消息:
导入声明只能出现在模块的顶层
告诉WordPress将自定义JavaScript作为模块处理的标准方法是什么?为了确保可以导入节点模块,我还需要执行其他步骤吗?您可以尝试从unpkg加载它
<script src="https://unpkg.com/package_name@version"></script>
希望这有帮助
告诉WordPress将自定义JavaScript作为模块处理的标准方法是什么
您所需要的只是
标记上的type=“module”
,浏览器将此脚本视为ECMAScript模块
使用wordpress,要在脚本上添加type
属性,首先将脚本排队
function enqueue_plugin_scripts() {
wp_enqueue_script('module_handle', get_template_directory_uri() . '/path/to/module.js')
}
add_action( 'wp_enqueue_scripts', 'enqueue_plugin_scripts' );
然后使用script\u loader\u标记将type=“module”
添加到module\u句柄
function set_scripts_type_attribute( $tag, $handle, $src ) {
if ( 'module_handle' === $handle ) {
$tag = '<script type="module" src="'. $src .'"></script>';
}
return $tag;
}
add_filter( 'script_loader_tag', 'set_scripts_type_attribute', 10, 3 );
这会奏效的
import "./node_modules/jquery/dist/jquery.js" //because jquery doesn't have browser-compatible ES module
import Swiper from "./node_modules/swiper/js/swiper.esm.browser.bundle.js";
import Swiper from 'https://unpkg.com/swiper/js/swiper.esm.browser.bundle.min.js'; //from external source
console.log($, Swiper) //will output jquery and swiper
这是一篇关于的好文章,你希望WordPress处理JS并以任何方式理解导入吗?我不是100%确定你到底想要完成什么。脚本和样式加载器所做的只是在页眉/页脚的脚本/链接标记中注册要吐出的URL/文件,以及一些简单的基于名称的依赖关系管理。或者您只是想在脚本标记上吐出type=module?我想说,在脚本标记中吐出type=module是加载其他节点模块的必要先决条件,是吗?假设是这样的话,这就是我要解决的主要问题。从那里,我可以把我的节点模块藏在任何旧的公共场所(或者创建一个脚本来实现),然后让它正常工作。通读注释,因为它们也解决了一个bug。基本上,您将不得不劫持打印功能并自行包含type=module
。此外,WordPress还有一个可以绑定每个句柄的功能,这可能会使打印时更容易识别。
import "./node_modules/jquery/dist/jquery.js" //because jquery doesn't have browser-compatible ES module
import Swiper from "./node_modules/swiper/js/swiper.esm.browser.bundle.js";
import Swiper from 'https://unpkg.com/swiper/js/swiper.esm.browser.bundle.min.js'; //from external source
console.log($, Swiper) //will output jquery and swiper