The WordPress coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. development team builds WordPress! Follow this site for general updates, status reports, and the occasional code debate. There’s lots of ways to contribute:
Found a bugbugA bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority.?Create a ticket in the bug tracker.
WordPress 6.7 introduces a new @wordpress/a11y script module and a new APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. to pass script module data from the server to the client.
Over the years of working on the GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ project, we developed some common practices. These help us preserve the quality and the long-term viability of the project. They differ and often contradict what people are used to in other projects (especially outside WordPress CoreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress.).
These practices should be applied during implementation and PR reviews. Sharing and embracing them helps contributors make the right decisions and be more autonomous when working on the project.
This list is non-exhaustive and subject to change. These are guidelines to always keep in mind but shouldn’t be treated as hard rules. Context is always important to consider.
Start APIs as private
Gutenberg is organized in packages. Implementing features means introducing new APIs to one or multiple packages. It’s important to understand that most of the packages‘ APIs are public WordPress APIs. Anything exported from a package and consumed by another package becomes a defacto WordPress APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways.. This API needs to be maintained forever to adhere with the WordPress backwards compatibility strategy. Thus, it’s recommended to start with private APIs.
Be intentional about providing public APIs
Extensibility is important to WordPress. We do want pluginPluginA plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party authors to extend what WordPress provides. We also want them to reuse tools that WordPress uses internally. This point can read as a contradiction with the previous one. But what’s important here is that it needs to be intentional. Before making an API public during the feature work, we should ask ourselves these questions:
Do we want to allow users to use this API?
And are we willing to support it for the next 10 years without breaking changes?
If the answer to both these questions is yes, then we can consider making this API public.
Avoid opening APIs for convenience, embrace copy/paste
Sometimes, for convenience and to abide to the DRY principle, we, developers create APIs and abstractions. This is seen as a good practice in most projects. But in the context of Gutenberg and WordPress, it is something to avoid. The cost of maintaining APIs is too high because of the backward compatibility strategy.
Say you have a low-level function or component already available to plugin authors or npm package users. To achieve their use-case, they maybe have to write some duplicate boilerplate code. Creating a higher-level abstraction to avoid the duplication should be avoided as much as possible. It is true that providing a great Developer Experience is important, though. There are cases where a higher-level abstraction is required. The main approach is that we should have very strong arguments for it and be intentional.
Prefer Semantic Extensibility
Plugin authors in WordPress want to be able to extend every piece of the UIUIUser interface. They also want to give way too much prominence to their own extensions and upsells. As WordPress history teaches us, this quickly leads to a degraded user experience. Who has never seen a WP Adminadmin(and super admin) with hundreds of notices? Who has never seen a WP Admin with menu items and call to actions competing for the user’s attention?
A non curated set of extensibility APIs can lead to stagnation as well. One example here is the metaMetaMeta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. boxes API in the classic editor and how it created a lot of constraints for the development of the blockBlockBlock is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. editor. These kinds of APIs prevent iteration and evolution. It becomes very hard to improve the UI and UXUXUser experience of these screens. Any change, no matter how small, can lead to breaking changes for plugin authors.
To alleviate these issues, extensibility in Gutenberg is curated and semantic. APIs to register/unregister semantic pieces (blocks, patterns, actions, fields) are preferred. APIs that are too broad and whose purpose is unclear should be avoided. For example:
A slot in the editor headerHeaderThe header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes. is not a very semantic API. It’s unclear what it will be used for. This will prevent any redesign and iteration to the header area of the editor.
The ability to set a priority or order to extensions is often an API that we want to avoid. It’s very prone to abuse. Often, plugins authors use these to give priority to their own extensions over what Core provides. It quickly leads to a degraded experience for users.
One package = one clear purpose
Developing features in Gutenberg often involves modifications to multiple packages at the same time. We need to ask ourselves: where should this piece of code live? To answer the question, it’s important to understand the purpose of each package. Here are some common examples:
Most of the editor UI is built within the @wordpress/block-editor package. So developers often change this package directly to accommodate their specific needs in the UI. The problem though is that it’s not the sole package responsible for adding UI to the editor. It is important to understand that this package is the Tinymce of Gutenberg. It can be used to build and integrate block editors within WordPress and outside WordPress. It’s a framework to build block editors. If a part of the UI is specific to WordPress, it’s not the right place to make this change. A recent example I noticed here is the addition of a button to the block settings menu. That button was used to open the WordPress editor sidebarSidebarA sidebar in WordPress is referred to a widget-ready area used by WordPress themes to display information that is not a part of the main content. It is not always a vertical column on the side. It can be a horizontal rectangle below or above the content area, footer, header, or any where in the theme., but editor sidebars are specific to WordPress block editors.
Making a REST APIREST APIThe REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. request in a UI component is another common pitfall that happens often. For example, you may want to build a Language Switcher UI component. And you want it to be reusable in the @wordpress/components package. You can’t use a REST API call within the component to fetch the available languages. The components package is a generic WP agnostic UI components package. So instead, it’s better to have a prop to pass of the available languages instead.
It’s also not recommended to add new packages just to share code between two existing packages. Usually, there’s a better solution to the code sharing problem. @wordpress/utils package doesn’t exist for a reason. Utility packages are a place where we can just dump shared code without purpose. As mentioned earlier, copy/pasting is not always a bad idea when it comes to code sharing. It is preferable to avoid early abstractions as much as possible.
Measure then optimize
We, developers have a tendency to over optimize our code. Often these optimizations involve adding some complexity to the code, making it harder to maintain. It is better to avoid these early optimizations. Instead, measure the impact of the change you want to perform to validate that the optimization is worth the added complexity. Important metrics are tracked in the codevitals dashboard.
Other random common pitfalls
Besides the principles above that one needs to follow to make the right calls, here are some common pitfalls that we’ve learned to avoid over time:
Avoid passing editor settings as inline JSJSJavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. from the backend to the frontend. It is a pattern we used heavily early in the project. We should ideally move away from it and prefer a better separation between client and server (use REST API calls).
Adding settings to the BlockEditorProvider (and the @wordpress/block-editor package) is ok. But we should be intentional about it: what does the setting mean for third-party block editors? Always remember the block editor framework use case.
Be declarative as much as possible. Using state actions and selectors to share UI state is acceptable. But know that it’s risky. It can lead to bugs and race conditions quickly if multiple components compete to set the right state. This happened to us at least in two recent situations:
Insertion position: We moved away from declaratively computing the insertion position based on the selected block. We used setInsertionPoint action and state instead. The issue is that the inserting point is now incorrectly set at times. Or it persists as we navigate away…
Block editing mode: To support different UI modes for blocks (content-only, locking, template-locked mode, zoom-out mode) we introduced a state to manipulate what we call “block editing mode” using setBockEditingMode action. We now have some hidden bugs because of that. These different modes compete to set the right block editing mode.
Avoid using stores in new packages. Be careful when introducing new data stores. Each time we register a new store, there’s added complexity in the system. Stores are singletons by default, they can only be present once in the page. We do support multiple instances of the same store on the page but it’s not without complexity. We need to extend the global registry. We have also seen that using stores in bundled packages like @worpdress/interface is not a good idea. When a plugin wants to use that package/store it leads to the store trying to be registered twice. The wrong store will be accessed from the components when it happens.
A new filterFilterFilters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. runs for each Script Module that is enqueued or in the dependency graph. This filter allows arbitrary data to be associated with a given Script Module and added to the rendered page.
Script Module data is embedded in the page as JSONJSONJSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. in a <script type="application/json">tagtagA directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.).
Script Modules are responsible for reading the data and performing their own initialization.
This is a proposal. Everything in this post is open to feedback and discussion. Please, share your thoughts and ideas.
The feedback period will end 2024-05-24 (Friday, May 24). Please provide any feedback before then.
This post will use “scripts” to refer to WP Scripts and “modules” to refer to WP Script Modules.
Scripts or modules?
Most JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. for WordPress is probably using scriptsunless it was specifically compiled as a module. Modern JavaScript is often authored using import apiFetch from '@wordpress/api-fetch', which is module syntax. Until very recently, WordPress build tooling has always removed the module syntax and compiled a script.
Only the most recent WordPress version 6.5 introduced support for modules. WordPress CoreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. includes exactly two modules to expose functionality at this time: @wordpress/interactivity and @wordpress/interactivity-router. JavaScript that uses the Interactivity APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. is probably a module.
This post will talk about a common script dependency, wp-api-fetch. The @wordpress/api-fetchmodule mentioned in this post is hypothetical; it does not exist at this time.
A note about modules
It’s important to know a few things about scripts versus modules in the context of this post. A few key differences:
Scripts and their dependencies will be executed as the page is parsed even if a dependency is never directly used.
Script “exports” are attached to the window object, e.g. wp-api-fetch is available as window.wp.apiFetch.
Modules will execute after the page has finished parsing.
Module dependencies can be loaded on demand.
Modules have true encapsulation, using import and export to share values.
More about scripts and modules…
Scripts that are either enqueued or are dependencies of enqueued scripts will be added to the page as script tags, like <script src="path/to/script.js">. The browser will fetch and execute these scripts before it continues to parse the page. There are attributes like async and defer that can change how the browser executes scripts.
Modules that are enqueued will appear on the page as script tags of type module, like <script src="path/to/module.js" type="module">. Processing of modules is deferred, they will be executed after the whole document has been parsed. The async attribute will cause a module to execute in parallel as the document is parsed. WordPress Script Modules do not use async at this time.
Modules that are in the dependency graph of enqueued modules will appear in an importmap. This is a mapping of names to URLs so that a browser knows what module to fetch when it sees an import. It’s what associates the module used in a statement like import "a-module"; with a URLURLA specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org{ "imports": { "a-module": "path/to/a-module.js" } }.
The problem
Scripts often require some initialization or other data to work correctly in WordPress. The wp-api-fetch script is a good example, it requires a significant amount of configuration. For example, Core uses the following inline script to initialize wp-api-fetch so it can send requests to the appropriate place:
This snippet uses PHPPHPThe web scripting language in which WordPress is primarily architected. WordPress requires PHP 7.4 or higher to create a string of JavaScript code with some data from PHP embedded. This will be included in a script tag that appears immediately after the script tag for wp-api-fetch, something like this:
<script src="path/to/wp-api-fetch.js"></script>
<script>
// The JavaScript code is printed here:
wp.apiFetch.use( wp.apiFetch.createRootURLMiddleware( "…/index.php?rest_route=/" ) );
// More code may follow from other calls to `wp_add_inline_script`…
</script>
Notice that the JavaScript depends on wp-api-fetch, it imperatively calls wp.apiFetch.use(…). That same approach with a hypothetical @wordpress/api-fetch module would look something like this:
In this approach, the initialization module would fetch and execute the @wordpress/api-fetch module just to initialize it! That eliminates one of the important advantages of modules, their ability to load on-demand. 🤔 It looks like this imperative initialization isn’t a good fit for modules. Let’s see if there’s a better solution…
The proposal
Here are some requirements that arise from the naive implementation:
Modules should be fetched and initialized on demand.
Modules should be responsible for their own initialization when they’re executed.
Variables should be scoped to modules and not pollute the global namespace.
The data should introduce minimal overhead.
Add server data via filters
Filters provide a nice method to collect the data needed by modules. The WP_Script_Modules class introduces a new filter that runs for each module that is enqueued or present in the dependency graph. Adding or modifying data for a module looks like this:
Multiple filters can be added to add or modify the data exposed to the script, and if no data is added, nothing will be serialized on the page for the client. It’s also worth mentioning that no JavaScript code is written in PHP, a nice improvement over wp_add_inline_script which requires valid JavaScript to be added.
A drawback to this approach is that all the data passed must pass through JSON. Data without a valid JSON representation is not supported by default.
Use an inert script tag to expose data on the client
The data is embedded it in the HTMLHTMLHyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. in a script tag:
<script id="scriptmoduledata_@wordpress/api-fetch" type="application/json">
{ "theData": "JSON Serializable data can be shared" }
</script>
Because modules are always deferred, it should be safe to print these script tags at the bottom of the page. They should have limited impact on page load because the browser will not parse or execute the contents.
Modules read data from the script tag
This script tag doesn’t do anything on its own. The module is responsible for getting the data and performing its initialization when it executes:
if ( typeof document !== 'undefined' ) {
const serializedData = document.getElementById(
'scriptmoduledata_@wordpress/api-fetch'
)?.textContent;
if ( serializedData ) {
let config = null;
try {
config = JSON.parse( serializedData );
} catch {
// there was a problem parsing the serialized data
}
performInitialization( config );
}
}
function performInitialization( config ) {
if ( config?.rootURL ) {
registerMiddleware( createRootURLMiddleware( config.rootURL ) );
}
// etc.
}
I’ve prototyped this proposal in the following PRs:
WordPress-develop PR 6433 applies the filters and adds the necessary filters to expose data to @wordpress/api-fetch. The proposal in this post is contained in this PR.
Gutenberg PR 60952 builds and registers the @wordpress/api-fetch module. This PR is helpful for testing, but is beyond the scope of this post.
Try it in the WordPress Playground here. If you run the following JavaScript in the inspector console —make sure you pick the JavaScript context, something like wp (scope:abc123)— you’ll see the @wordpress/api-fetch module log some initialization when it’s imported and then work as expected:
As the web continues to evolve, so does our approach to building and managing JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. in WordPress. Looking to the future, a collaborative effort is underway to explore native support for modern JavaScript modules and import maps within the WordPress ecosystem. This exploration is geared towards enhancing the developer experience by embracing the capabilities of modern browsers.
Introduction
JavaScript modules have transformed the way developers write and organize JavaScript code. They provide a cleaner and more modular architecture, making code easier to maintain, test, and reuse across projects. Today, the vast majority of web browsers offer native support for JavaScript module syntax, offering performance benefits and unlocking new possibilities in how we develop and manage client-side scripts.
In this realm, it becomes essential for WordPress to keep pace with these advancements and start experimenting with the addition of native support for registering and enqueueing JavaScript modules — including generating an import map directly within WordPress.
The primary objectives of this initiative are:
To leverage the native JavaScript module system available in modern browsers.
To streamline the development process in WordPress using JavaScript modules.
To determine the most efficient and effective methods for handling dependencies and optimizing loading times.
Prior discussions and experiments
The following links are some preliminary discussions and experiments that touch upon JavaScript modules and related approaches to script loading within the WordPress ecosystem:
However, the journey toward a modern, module-friendly WordPress is still in its early stages, and the next steps will be instrumental in deciding how best to integrate module support in a way that benefits developers and users alike, without disrupting the stability and familiarity of the current WordPress experience.
The experimentation phase
The current plan involves conducting initial experiments within the GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/pluginPluginA plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party. By exploring within this semi-contained environment, contributors will gain practical insight into constructing modules that are compatible with WordPress’ existing infrastructure. This experimentation will help make informed decisions on several fronts:
Deciding whether to extend the existing wp_enqueue_script function or introduce a distinct APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. (like wp_enqueue_module).
Evaluating whether to maintain dependencies on the server vs relying completely on the client’s native resolution.
Establishing best practices for module identifiers, dependency registration, inline modules, preloading optimizations, and more.
Assessing integration challenges and ensuring backward compatibility.
It’s worth noting that while the experimentation will be kicked off using a separate API for simplicity’s sake, this doesn’t necessarily predetermine the final form of the proposal.
After conducting experiments, collecting insights, and incorporating the feedback received, an update that will outline a more specific implementation plan will be provided.
Potential enhancements such as dependency auto-detection and additional performance optimizations could be incrementally introduced later on.
Your input is important
Your perspective is crucial to the success of this initiative. Whether you are a plugin author, theme developer, coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. contributor, or anyone interested in the future of JavaScript in WordPress, join us in shaping a robust and forward-looking solution.
Get involved!
You are invited to participate in this exploratory phase and contribute your ideas, concerns, and suggestions. Below are some prompts to get the conversation started:
How do you currently manage JavaScript modules within your WordPress projects?
What challenges have you faced with the existing script enqueueing system?
In what ways can native support for JavaScript modules improve your development workflow?
Are there specific use cases or scenarios where you feel this proposal could greatly benefit you or the WordPress community?
Please share your thoughts in the comments below, on Trac, or participate in the ongoing discussions and experiments on GitHub. Your engagement is invaluable to work together toward a more modern, module-friendly WordPress.
This post outlines a proposal to add a script loading strategy enhancementenhancementEnhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. to coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress.’s existing Scripts APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways..
The underlying goal of this effort is to make it easier for WordPress pluginPluginA plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party and theme developers and core to use “modern” loading approaches for JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. (like defer and async), which will help WordPress sites load faster and operate more smoothly, giving users a better experience.
Why add a loading strategy?
Data from the Web Almanac project (query) indicates that render blocking JavaScript is a significant problem on the web, with 77% of mobile pages having render-blocking scripts in the document <head> . This query shows that approximately 40% of WordPress sites stand to benefit from deferring additional scripts. Adding defer or async to script tags enables script loading without “blocking” the rest of the page load, resulting in more responsive sites overall better user experience.
Currently WordPress core as well as plugins and themes register scripts with the wp_enqueue_script and/or wp_register_script functions. Although these functions include the ability to control the placement of the script (with the in_footer parameter), they don’t include support for adding modern attributes such as defer or async to script tags.
To add async or defer today, developers must resort to less flexible and more fragile approaches, such as directly filtering the tags at the point of output (using the script_loader_tagfilterFilterFilters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output.), or handling the tagtagA directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) output directly using wp_print_script_tag and the wp_script_attributes filter.
Using the first approach and directly filtering the tag can easily break: for example if two plugins both try to filter a tag, or if a tag has unexpected attributes already (eg. adding defer to a tag that already has async). Using the the second approach developers must carefully handle dependencies and output manually – things that that the Scripts API usually helps take care of.
How the loading strategy works
Developers specify a loading strategy when registering or enqueueing a script. For example, a defer strategy can be specified when the script isn’t required immediately during the page load cycle. WordPress will then determine which scripts can actually use a strategy based on logic for each strategy. For example, to ensure that scripts are executed in the order they are enqueued, defer can only be used on a script if every script that depends on that script can also be deferred. Inline script tags added with wp_add_inline_script would also be considered to ensure proper execution order.
The implementation would come with several initial built-in loading strategies: defer, async, and the default blocking behavior.
Out of scope for this feature
The loading strategy does not enable direct control of script tag attributes. This idea was originally proposed 10 years ago in #22249 and several approaches were considered on that ticketticketCreated for both bug reports and feature development on the bug tracker. including a script attribute filter. This proposal takes a step back and aims to solve the script loading strategy aspect more comprehensively and directly while avoiding exposing the potential complications of direct attribute control.
It is worth noting that it is already possible to control attributes on wp_enqueue_script tags directly using the script_loader_tag filter. However, this is a bit of a “brute force” approach which is limited and fragile because it doesn’t consider dependencies and multiple plugins can take conflicting actions on the same tag.
What are potential concerns with this feature?
One big concern with adding this feature to the WordPress Script API is potentially introducing a breaking change. wp_enqueue_script is a fundamental API in WordPress core, and any breaking changes could have widespread implications. Possible breakage is a possible reason that adding custom attributes as proposed in #22249 was never added to core.
This new proposal aims to ensure that there is 100% backwards compatibility, resulting in zero risk of breakage. The loading strategy will ensure that all existing uses continue to function as expected; for example, passing the boolean in_footer attribute will still control script placement. In addition, it will ensure that scripts continue to be executed in the order they are enqueued – as described above in the “How the loading strategy works” section.
Conclusion and Next Steps
Giving developers the ability to specify a loading strategy will enable them to use more advanced JavaScript loading methods while still ensuring that enqueued scripts are executed in the correct order. A “strategy” approach is also forward thinking: as the web evolves, new strategies can be developed and made available to WordPress developers. After gathering feedback, we will proceed to discussing the implementation approach and, ultimately, proposing a patchpatchA special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing..
Have you tried using defer or async with WordPress (or do you already)? How do you think this enhancement would change that? Please leave your feedback about this proposal in the comments below and if you can, join us at our weekly performance team chats, where we are likely to discuss this proposal in the future.
Thanks to @flixos90, @tweetythierry and @mxbclang for help writing and reviewing this post and for the many contributors who have added to the discussion around this enhancement already.
TLDR; We made WordPress packages publishing to npm more predictable by synchronizing it with bi-weekly GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/pluginPluginA plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party RC1 release. We no longer have to keep the process tightly coupled with WordPress major releases.
Revised branching strategy for npm publishing
The Gutenberg repository still follows the WordPress SVN repository’s branching strategy for every major WordPress release. In addition to that, there are two other special branches that control npm publishing workflows and they are used as follows:
The wp/latestbranchbranchA directory in Subversion. WordPress uses branches to store the latest development code for each major release (3.9, 4.0, etc.). Branches are then updated with code for any minor releases of that branch. Sometimes, a major version of WordPress and its minor versions are collectively referred to as a "branch", such as "the 4.0 branch". contains the same version of packages as those published to npm with the latest distribution tagtagA directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.). The goal here is to have this branch synchronized with the last Gutenberg plugin release, and the only exception would be unplanned Standalone Bugfix Package Releases (read more below).
The wp/next branch contains the same version of packages as those published to npm with the next distribution tag. It always gets synchronized with the trunk branch. Projects should use those packages for development or testing purposes only.
A Gutenberg branch wp/* (example wp/6.0) targeting a specific WordPress major releasemajor releaseA release, identified by the first two numbers (3.6), which is the focus of a full release cycle and feature development. WordPress uses decimaling count for major release versions, so 2.8, 2.9, 3.0, and 3.1 are sequential and comparable in scope. (including its further minor increments) gets created based on the wp/latest Gutenberg branch just after the last Gutenberg release planned for inclusion in the next major WordPress release.
Release types and their schedule:
Synchronizing Gutenberg Plugin (latest dist tag) – publishing happens automatically every two weeks based on the newly created release/* (example release/12.8) branch with the RC1 version of the Gutenberg plugin.
WordPress Releases (patch dist tag) – publishing gets triggered manually from the wp/* (example wp/6.0) branch. Once we reach the point in the WordPress major release cycle (usually after BetaBetaA pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process. 1) where we only cherry-pick commits from the Gutenberg repository to the WordPress coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress., we use wp/* branch (created from wp/latest) for npm publishing with the patch dist-tag. It’s also possible to use older branches to backportbackportA port is when code from one branch (or trunk) is merged into another branch or trunk. Some changes in WordPress point releases are the result of backporting code from trunk to the release branch. bugs or security fixes to the corresponding older versions of WordPress Core.
Development Releases (next dist tag) – it is also possible to perform development releases at any time when there is a need to test the upcoming changes.
There is also an option to perform Standalone Bugfix Package Releases at will. It should be reserved only for critical bugbugA bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. fixes or security releases that must be published to npm outside of regular cycles.
The complete documentation is available in the BlockBlockBlock is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. Editor Handbook.
Running npm publishing with GitHubGitHubGitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ workflows
While the npm publishing got configured to happen automatically every two weeks as part of the Gutenberg plugin release workflow, there might still be cases when other release types need to be executed. To start the process, go to Gutenberg’s GitHub repository’s Actions tab, and locate the “Publish npm packages” action. Note the blue banner that says “This workflow has a workflow_dispatch event trigger.”, and expand the “Run workflow” dropdown on its right-hand side.
There are three ways to publish packages to npm depending on the their type:
WordPress major release – select wp from the “Release type” dropdown and enter X.Y (example 5.9) in the “WordPress major release” input field.
Development release – select development from the “Release type” dropdown and leave “WordPress major release” input field empty.
Bugix release – select bugfix from the “Release type” dropdown and leave “WordPress major release” input field empty.
Finally, press the green “Run workflow” button. It triggers the npm publishing job, which needs then to be approved by a Gutenberg Core team member.
Testing JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. code from a specific major WordPress version
An interesting bonus got included with the revised workflow for npm publishing related to WordPress major releases. It’s now possible to quickly install a version of the individual WordPress package used with a given WordPress version using distribution tags (example for WordPress 5.8.x):
npm install @wordpress/block-editor@wp-5.8
It’s also possible to update all WordPress packages in the project with a single command:
I propose switching to the original version of the Prettier code formatting tool in the GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ project and updating it to the most recent 2.5 version. Consequently, we should apply the necessary changes to the existing WordPress JavaScript Coding Standards around spacing to respect Prettier’s capabilities.
Code formatting challenges
It’s worth reminding that this topic was discussed several times, beginning in 2017 when the initial exploration of using Prettier started with WordPress/gutenberg#2819. Throughout all that time, the Prettier maintainers didn’t change their mind about adding support for spaces between parens (()) and brackets ([]) despite many requests shared in prettier/prettier#1303 from users (including the WordPress community). That’s why we decided to apply the first batch of JavaScript Coding Standards revisions two years later to use the forked version of Prettier developed by developers at Automattic. It allowed us to remain aligned with the coding style conventions used for PHPPHPThe web scripting language in which WordPress is primarily architected. WordPress requires PHP 7.4 or higher in the WordPress codebase. In particular, to follow these rules:
Use spaces liberally throughout your code. “When in doubt, space it out.”
The WordPress JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. standards prefer slightly broader whitespace rules than the jQuery style guide. These deviations are for consistency between the PHP and JavaScript files in the WordPress codebase.
The issue is that we ended up with an outdated fork of Prettier in the Gutenberg project that didn’t get any updates for more than a year. The only motivation behind using a custom version of Prettier remains its additional functionality overriding formatting behavior for spaces around parens and brackets. In the meantime, there were three minor releases of Prettier with a long list of new features in the last year:
The Gutenberg project no longer uses only JavaScript for development. Some parts of the codebase use TypeScript, which we agreed upon a few months back. It means we can’t use improvements added for newer versions of the TypeScript language and potentially for future additions to the JavaScript language. A deprecation was also added to one of the config options we use in the shared Prettier config that the community uses. It turns out that it prevents using the @wordpress/prettier-config package with the most recent version of Prettier in 3rd party projects, as explained in WordPress/gutenberg#37516. Finally, we had multiple reports in WordPress/Gutenberg#21872 from the community members using @wordpress/scripts or @wordpress/eslint-plugin packages that the forked version of Prettier doesn’t install correctly in their projects. The good news is that switching to the original Prettier will resolve all of the above!
It quickly became noticeable that the automatic code formatting saves you so much time and energy when trying to keep a consistent coding style in the project. This is why we also started using Prettier to format other types of files it supports in the Gutenberg project, like JSONJSONJSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML., YAML, Markdown. We also consider doing the same for CSSCSSCascading Style Sheets. and SCSS next.
RevisionsRevisionsThe WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision. to JavaScript Coding Standards
I propose we apply all the necessary changes to the WordPress JavaScript Coding Standards to switch to the latest available version of Prettier (2.5 as of writing). The excerptExcerptAn excerpt is the description of the blog post or page that will by default show on the blog archive page, in search results (SERPs), and on social media. With an SEO plugin, the excerpt may also be in that plugin’s metabox. of the most significant revisions is included below.
-Some whitespace rules differ, for consistency with the WordPress PHP coding standards.
+Some whitespace rules differ, for consistency with the [Prettier](https://prettier.io) formatting tool.
-All new or updated JavaScript code will be reviewed to ensure it conforms to the standards, and passes JSHint.
+All new or updated JavaScript code will be reviewed to ensure it conforms to the standards, and passes [ESLint](https://eslint.org).
-Use spaces liberally throughout your code. “When in doubt, space it out.”
-Any ! negation operator should have a following space.*
+Any ! negation operator should not have a following space.
-Always include extra spaces around elements and arguments:
-array = [ a, b ];
-foo( arg );
-foo( 'string', object );
-foo( options, object[ property ] );
-foo( node, 'property', 2 );
-prop = object[ 'default' ];
-firstArrayElement = arr[ 0 ];
+Never include extra spaces around elements and arguments:
+arg = [a, b];
+foo(arg);
+foo('string', object);
+foo(options, object[property]);
+foo(node, 'property', 2);
+prop = object['default'];
+firstArrayElement = arr[0];
-var i;
-
-if ( condition ) {
- doSomething( 'with a string' );
-} else if ( otherCondition ) {
- otherThing( {
- key: value,
- otherKey: otherValue
- } );
-} else {
- somethingElse( true );
-}
-
-// Unlike jQuery, WordPress prefers a space after the ! negation operator.
-// This is also done to conform to our PHP standards.
-while ( ! condition ) {
- iterating++;
-}
-
-for ( i = 0; i < 100; i++ ) {
- object[ array[ i ] ] = someFn( i );
- $( '.container' ).val( array[ i ] );
-}
-
-try {
- // Expressions
-} catch ( e ) {
- // Expressions
-}
+var i;
+
+if (condition) {
+ doSomething('with a string');
+} else if (otherCondition) {
+ otherThing({
+ key: value,
+ otherKey: otherValue,
+ });
+} else {
+ somethingElse(true);
+}
+
+while (!condition) {
+ iterating++;
+}
+
+for (i = 0; i < 100; i++) {
+ object[array[i]] = someFn(i);
+ $('.container').val(array[i]);
+}
+
+try {
+ // Expressions
+} catch (e) {
+ // Expressions
+}
You can preview the impact on the Gutenberg codebase on GitHubGitHubGitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ in the exploratory Pull Request. The same changes would impact the tooling recommended for blockBlockBlock is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. development like @wordpress/create-block and @wordpress/scripts.
When will a decision be made?
Let’s plan for making a decision three five (updated on Jan 25th) weeks from the date of publication of this post. That should give enough time for discussion and questions.
Hi folks! I’m back again with an update on the TypeScript proposal. Previously in the follow-up post I said that after two weeks we would make a decision about it. It’s been several months since then, so it’s about time to make that decision!
While there was some feedback to the proposal, nothing was raised that seemed to blockBlockBlock is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. the integration of native TypeScript into the GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ project. Indeed, some packages (like compose and components) have seen a great deal of native TypeScript introduced. In fact, compose today is fully typed and this would not be the case if it were not for native TypeScript support in Gutenberg.
Therefore, I’d like to officially announce that the Gutenberg project supports native TypeScript. We will continue to follow the guidelines laid out in the follow-up proposal, reproduced here for posterity.
For existing code:
The default is to use JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/.
When it is possible to type something simply with JSDoc, use JSDoc
If there are complex types, but JSDoc is still sufficient generally for consuming those types, you may extract the complex types into a types-only types.ts file to be imported into the JSDoc
If it is not possible to express the types using JSDoc or if the JSDoc will vastly over-complicate the ability to type a function, convert it to TypeScript
For new code:
Use TypeScript when working in a “low-level package” (as defined below) for new code. Otherwise, follow the same pattern laid out for the existing code.
Low level packages:
A low level package is a package that:
Provides a public APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways.; and
Attendance at the CoreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress.JSJSJavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. Office hours has been low for the last few weeks so at the most recent chat those that were present decided that we’d move to a bi-weekly cadence for now. Here’s a quick summary of what is happening:
Core JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. office hours will be bi-weekly at the same time slot (15:00UTC) with the next meeting happening July 27th.
Whenever there is something requiring more attention, the suggestion is to schedule a dedicated meeting for interested parties to gather together in the #core-jsSlackSlackSlack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel to have the discussion.
A reminder that the #core-js channel and office hour chats are intended to cover JavaScript across all of WordPress core, all JavaScript infrastructure, tools that build, lint, or test JavaScript code and higher-level discussions about coding styles, libraries used, etc. So has some distinction (even though there can be some overlap) from the kinds of discussions that happen within the #core-editor Slack instance which focuses predominately on the GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ project and its implementation within WordPress.
The proposal to intentionally integrate native TypeScript into the GutenbergGutenbergThe Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ repository has garnered overwhelmingly positive feedback so far. However there have been some responses that express concerns over introducing a new technology that will be difficult for contributors to understand. This follow up will hopefully address some of those concerns by refining and clarifying some of the ideas in the original proposal.
In this proposal, nothing changes for consumers of Gutenberg packages (like blockBlockBlock is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. developers). JavaScriptJavaScriptJavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. remains the primary way of interacting with the APIAPIAn API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways.. If block developers opt-in to use TypeScript for their own projects, we will gradually improve the tools and typings to make their experience better.
Let’s remember why it’s important to introduce TypeScript and strongly typed functions:
A better developer experience via automatic code completion (like Intellisense) and other related tools
More confidence in our code through better static analysis of function internals and their usages
When to use TypeScript for existing code
So, with that in mind, I’d like to propose @gziolo’s method for approaching when to use TypeScript for existing files:
The default is to use JavaScript
When it is possible to type something simply with JSDoc, use JSDoc
If there are complex types, but JSDoc is still sufficient generally for consuming those types, you may extract the complex types into a types-only types.ts file to be imported into the JSDoc
If it is not possible to express the types using JSDoc or if the JSDoc will vastly over-complicate the ability to type a function, convert it to TypeScript
This, of course, only applies to the places that support native TypeScript anyway which is currently limited to mostly lower level packages, which are the primary initial targets for typing. This falls in line with the original proposal’s statement that “the majority of Gutenberg will probably forever remain as plain old JavaScript.”
It does not cover the case for fully new code in existing packages or new code in the form of completely new packages.
When to use TypeScript for new code
Therefore, for the now rare occasion when a fully new package is added, if all the dependencies are typed, I would like to propose that these should be added in native TypeScript. Likewise, packages that are fully typed or are currently being worked on towards full typing (see #18838 for the list of typed and in-progress packages) and fall into the categoryCategoryThe 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging. of “lower level packages” as described here and in the next section should have new code added in TypeScript.
Otherwise, new code should follow the the same logic laid out above for existing files, essentially only using TypeScript when absolutely necessary, preferring JSDoc typed JavaScript.
Lower level packages
A note about “lower level packages.” We can refine this definition slightly by stating that a low level package is a package that:
When refactoring existing code to add types, follow the script above.
For new packages, use native TypeScript when a) all the packages dependencies are typed and b) when they fall into the category of “lower level packages” as defined above.
For new code in existing packages, follow the same script above as for refactoring existing code.
If this is accepted by the community then I will open a PR to update the JavaScript coding guidelines in the repository to reflect this. The update will include the script set out above.
When will a decision be made?
I’d like to aim for making a decision 2 weeks from the date of publication of this follow up post. That should give ample time for discussion and questions.
You must be logged in to post a comment.