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.
Next, run the following command:
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:
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.