All packages that the modern WordPress JavaScript uses are available as @wordpress/
packages. This means that a simple npm install @wordpress/data
will get you the data module. The same that is used in WordPress. The challenge with this is that this code will be duplicated between WordPress and your plugin. Bundlers like webpack and browserify include all the code in @wordpress/data
inside your built JavaScript file. To remedy this you can configure your bundler to use the available package from a global variable instead. For @wordpress/data
this global is wp.data
.
Your PHP configuration needs to be changed to accomodate this. When you use wp.data
you need to make that script a dependency of your script. You can do this by providing it in the dependency array of wp_register_script
:
wp_register_script( 'script-handle', 'path-to-script.js', array( 'wp-data' );