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' );
This will make sure that wp.data
will be available for your script.
To configure webpack to use wp.data
you can use the externals
configuration option. So in the case of @wordpress/data
you would provide the following configuration to webpack:
{
// Other configuration...
externals: {
"@wordpress/data": "window.wp.data",
}
}
This tells webpack to replace import data from "@wordpress/data"
and const data = require( "@wordpress/data" )
with wp.data
instead.
In Rollup this can be achieved using output.globals
.