Enqueuing scripts
This boilerpate includes @wordpress/scripts, a package from the WordPress project that provides various development tools, including a pre-configured Webpack thatβs already with specific needs for WordPress. This setup means we donβt have to worry about configuring Webpack, Babel, or other tools to compile our scripts. We can just focus on writing your code.
Adding a script
To add a new script to enqueue, start by creating a file named index.js in the src folder. For example, if you want to add a custom script for the admin area, create a new directory named admin, and then create an index.js file inside that directory.
.βββ appβββ incβββ src βββ admin β βββ index.js βββ blocksNext, run the following command:
npm run startThis command scans the src/ directory and its subdirectories for any entry point file named index.js. It then transforms the code and automatically rebuilds if you make changes to any of the files. Any build errors will be displayed in the console.
The built files will be saved in the dist directory. In this example, youβll find three files related to the admin.js file:
.βββ appβββ distβ βββ admin.jsβ βββ admin.js.mapβ βββ admin.asset.phpβββ incβββ src βββ admin β βββ index.js βββ blocksadmin.jsis the compiled JavaScript file that you can enqueue in your plugin.admin.js.mapis the source map file that helps you debug the code in the browser.admin.asset.phpcontains the metadata of the script that you can use to enqueue the script in WordPress.
Enqueuing the Script
To enqueue the script, we can use the helper function, WPStarterPlugin\enqueue. The function is wrapper to the Enqueue object from from the syntatis/wp-helpers package. It provides an abstraction that wire these compiled files together and makes makes enqueuing the files less of manual work.
In this example, weβve created a file named Admin.php and used this helper function to enqueue our admin script in the admin area.
namespace WPStarterPlugin;
use WPStarterPlugin\Vendor\Syntatis\WPHook\Contract\WithHook;use WPStarterPlugin\Vendor\Syntatis\WPHook\Hook;
class Admin implements WithHook{ public function hook(Hook $hook): void { $hook->addAction('admin_enqueue_scripts', [$this, 'enqueueScripts']); }
public function enqueueScripts(): void { $enqueue = enqueue(); $enqueue->addScript('admin'); }}