Enqueueing using the from @wordpress/scripts generated .deps.json dependencies [UPDATED for .asset.php]

When using the @wordpress/scripts package, it will automatically create a .deps.json file for every JavaScript entrypoint. This file contains a list of all the WordPress JavaScript dependencies used in it and in all the file it imports. Therefore it really simplifies keeping track all of the dependencies of a script.

But the question that quickly came to mind is how to actually properly use it as the script dependencies. And how to add your own dependencies to it, if you are relying on your own ones as well.

The way I found easiest, is by using a ternary statement. First I check wether the file exists. If so I json_decode the file contents. If the file does not exist I just return an empty array.

In my register or enqueue script function I then use array_merge to merge the script dependencies from the .deps.json file and my own custom scripts that I need to depend on.

$block_path = 'build/index.js';
$script_deps_path = plugins_url('build/index.deps.json', __FILE__);
$script_dependencies = file_exists($script_deps_path)
    ? json_decode(file_get_contents($script_deps_path))
    : [];
    plugins_url($block_path, __FILE__ ),
    array_merge($script_dependencies, []),

UDATPE @wordpress/scripts ^5.0.0

With the new Version 5.0.0 of the @wordpress/script package they switched from having generated JSON files for storing the dependencies to having a .asset.php file for each of the js entry points. These files return an array containing another array of dependencies and a string for the version of that file. To access them you can easily use a php include statement and store it in a variable. From there you can access the named elements in the array. Like I mentioned, at the moment there are only the dependencies and the version. But the plan seems to be expanding that in the future to make enqueueing easier and easier.

$block_path = 'build/index.js';
$script_dependencies = ( include plugins_url( '/build/index.asset.php' , __FILE__ );
    plugins_url($block_path, __FILE__ ),
    array_merge( $script_dependencies['dependencies'], [),

2 Replies to “Enqueueing using the from @wordpress/scripts generated .deps.json dependencies [UPDATED for .asset.php]”

  1. Florian Brinkmann says:

    Hi Fabian,

    wow, I never took a closer look at those auto-generated files, but that is very useful — thanks for writing the article!


    1. Fabian Kägy says:

      Hi Florian,

      Yeah it’s one of those small things that make development just that tiny bit easier that I am always missing is when projects don’t do it now 😅

Leave a Reply

Your email address will not be published. Required fields are marked *