javascript - 在 WordPress 插件中导入 Node 模块

标签 javascript php node.js wordpress

我正在使用 wp_register_scriptwp_enqueue_script为我正在开发的 WordPress 插件的管理屏幕引入一些自定义 JavaScript 逻辑。
当我尝试添加 import 时出现问题语句在我的 JavaScript 顶部,以便引入几个 Node 模块。可以理解,这给了我以下浏览器控制台消息:

import declarations may only appear at top level of a module


告诉 WordPress 将自定义的 JavaScript 位视为模块的标准方法是什么?为了确保可以导入我的 Node 模块,我还需要遵循其他步骤吗?

最佳答案

What is the standard way to tell WordPress to treat a custom bit of JavaScript as a module?


您只需要type="module"<script>标签,浏览器会将此脚本视为 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' );
然后添加 type="module"module_handle使用 script_loader_tag
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 );

And are there other steps I need to follow in order to make sure that my node modules can be imported?


您不能使用裸导入,例如:import $ from "jquery"将在浏览器中失败。
node_modules 导入,您必须提供模块的完整路径,否则浏览器
会投诉 Relative references must start with either "/", "./", or "../"下面是一些例子:
这行不通
import $ from "jquery";
import Swiper from "swiper";
这将工作
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
这是一篇关于ECMAScript modules in browsers的好文章

关于javascript - 在 WordPress 插件中导入 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62553169/

相关文章:

javascript - MongoDB:如何返回 JSON 中的特定字段和特定子文档

mysql - 通过 sails-disk mysql 适配器或 Nodejs 应用程序中的 mysql 查询数据库字段中值为 'null' 的某些数据

javascript - Chrome 和 Firefox 的 window.close() 方法的替代方法

javascript - 单击时 Div 平滑扩展至全屏

PHP 查询结果存入变量

PHP:从数组中选择 child

javascript - 在 TypeScript 中使用索引签名时如何将值类型与键匹配?

javascript - 同时使用 panTo 和 panBy

php 和 mysql 帮助,使用多个数据库

javascript - Node.js + Socket.io : Client not receiving message