Gutenberg comes with a set of core libraries which are necessary for any kind of custom block development. Namely those libraries are:
- @wordpress/components: Generic, reusable UI WordPress components
- @wordpress/i18n: Internationalization utilities
- @wordpress/element: Abstraction on top of React
- @wordpress/date: Date formatting and manipulation utilities
- @wordpress/blocks: Module providing utilities for registering and building blocks
- @wordpress/data: Abstraction on top of Redux
- @wordpress/editor: Module representing the WordPress Editor’s page
- @wordpress/utils: Various generic utilities
To use them you need to include them as external script requirements to your final build by registering and enqueueing them, similarly to how you’d include any kind of script or style within WordPress.
The above then will be loaded as separate scripts and available through the global object (the
window object since we’re in a browser environment) and we’d use them as with any externally loaded script in our code:
If you’ve been using ESNext (which I strongly suggest you do) with a build step that includes
webpack, you could define these libraries as externals in your webpack configuration and use them as ES modules!
First we need to define our
libraryTarget output in webpack’s config:
This is required so that webpack knows exactly to which context to assign the global variables to. Then we define Gutenberg’s libraries as externals, again in webpack’s config on its
Or we can be a bit smarter and avoid declaring every single one manually:
And that’s it, from now onwards we can “import” Gutenberg’s external libraries as ES modules:
Of course they won’t be included in our final build, this is mostly so that we keep a consistent usage syntax for our external dependencies. Another benefit is that if WordPress ever releases them as standalone
npm packages our migration path will be much easier, especially if we name them
@wordpress/data instead of
wp.data (the name you give is your choice).
This is very helpful!!
I’ve a question: how is possible to include a custom .js file?