Building JavaScript

The Gutenberg Handbook shows JavaScript examples in two syntaxes: ES5 and ESNext. These are version names for the JavaScript language standard definitions. You may also see elsewhere the names ES6, or ECMAScript 2015 mentioned. See the ECMAScript Wikipedia article for all the details.

ES5 code is compatible with WordPress’s minimum target for browser support. It can run straight in your browser and does not require an additional build step. In many cases, it will be perfectly fine to follow the same approach to start experimenting with your plugin or theme quickly. As soon as your codebase grows to hundreds of lines, it might be a good idea to take advantage of all the great JavaScript features included in ESNext syntax.

With the release of Gutenberg 5.3, the @wordpress/scripts package was updated to include webpack and Babel configurations. The update makes setting up an ESNext development environment much easier for building blocks and creates a standard method for developers to set up their plugin.

The documentation in the JavaScript tutorial and the ESNext examples in the gutenberg-examples repository are both updated to include the new process.

Here is a quick overview of how to set up an environment. First, you need to install @wordpress/scripts package:

npm install --save-dev @wordpress/scripts

You can then update the scripts section of your package.json to include:

"scripts": {
    "start": "wp-scripts start",
    "build": "wp-scripts build"
}

No webpack config (e.g., webpack.config.js) or Babel config (e.g., .babelrc) is needed.

The scripts expect the source file to be found at src/index.js and will output the build to build/index.js. So if you are migrating an existing plugin, you will need to move your source and enqueueing to these new locations.

With the setup in place, the standard workflow is:

  • Install dependencies: npm install
  • Start development builds: npm start
  • Develop. Test. Repeat.
  • Create production build: npm run build

In general, the package should be used with the set of recommended config files. While it is possible to override every single config file provided, if you have to, it means that your use case is more complicated than anticipated. We’d love hearing about it as we’d like to iterate on the current setup and offer more flexibility in the future. At the moment, our recommendation would be to use the underlying tools (webpack, Babel) directly.

See the JavaScript Build Setup documentation for a full explanation and walk through, and see the scripts package documentation for all the details.

Props to @gziolo and @nosolosw for their efforts.

#core-editor, #core-js, #javascript