1 回答

TA貢獻1836條經驗 獲得超4個贊
告訴 WordPress 將 JavaScript 的自定義位視為模塊的標準方法是什么?
您所需要的只是在標簽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_handleusingscript_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 );
為了確??梢詫胛业墓?jié)點模塊,我還需要遵循其他步驟嗎?
您不能使用裸導入,例如: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

TA貢獻1797條經驗 獲得超6個贊
您可以嘗試從 unpkg 加載它
<script src="https://unpkg.com/package_name@version"></script>
希望這可以幫助。
- 1 回答
- 0 關注
- 169 瀏覽
添加回答
舉報