Since I work a lot using WordPress, I was wondering if I could put a Svelte app on an admin WordPress page. As I found out, it’s not that complicated to achieve this – but you do need some tinkering. Initially, we must define the admin page as so:
add_menu_page( "Menu Name, "Menu Name, "manage_options", "menu_slug", function(){
});
Notice I’m using an anonymous function to render the page. In the function I will enqueue the script and style of the app as follows:
add_menu_page( "Menu Name, "Menu Name, "manage_options", "menu_slug", function(){
wp_enqueue_script( 'bundle_js',plugins_url( 'js/' . "bundle.js", __FILE__ ) ,array(), 1.1, true );
wp_enqueue_style( "bundle_css",plugins_url( 'css/' . "bundle.css", __FILE__ ));
});
This is almost adequate. But Svelte targets the body of the document, so some minor amendments will be needed to do the trick.
First, have Svelte target some unique tag in your main js file:
const app = new App({
target: document.querySelector("my-special-tag")
});
Secondly, add one more piece of code to your add_menu_page
call:
add_menu_page( "Menu Name, "Menu Name, "manage_options", "menu_slug", function(){
echo "<my-special-tag/>"; // add this
wp_enqueue_script( 'bundle_js',plugins_url( 'js/' . "bundle.js", __FILE__ ) ,array(), 1.1, true );
wp_enqueue_style( "bundle_css",plugins_url( 'css/' . "bundle.css", __FILE__ ));
});
That’s it! Providing that you copied the Svelte code to the relevant directories in your plugin- everything should work! I also recommend reading my post about Hash File Suffixing to prevent the browser from caching your scripts.