Skip to content

Instantly share code, notes, and snippets.

@atimmer
Created September 18, 2018 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atimmer/ac542338b8da8a282def91568f164819 to your computer and use it in GitHub Desktop.
Save atimmer/ac542338b8da8a282def91568f164819 to your computer and use it in GitHub Desktop.

Gutenberg externals

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.

Webpack

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.

Rollup

In Rollup this can be achieved using output.globals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment