Skip to content

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
└── blocks

Next, run the following command:

Terminal window
npm run start

This 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
└── blocks
  • admin.js is the compiled JavaScript file that you can enqueue in your plugin.
  • admin.js.map is the source map file that helps you debug the code in the browser.
  • admin.asset.php contains 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.

src/Admin.php
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');
}
}