Understanding and Using @wordpress/scripts in Plugin Development

Yesterday, WordPress 5.2 was released. In addition to increasing the PHP version requirement to 5.6.20 and adding a wp_body_open hook, this version also introduced the updated @wordpress/scripts tool.

Simply put, @wordpress/scripts is a module build tool provided for Gutenberg block development. If you need more information about this tool, please refer to the JavaScript Build Setup article in the Gutenberg Handbook.

Gutenberg supports both ES5 and ESNext JavaScript syntax. ES5 syntax matches the support situation in WordPress browsers, can run directly in browsers, and does not require additional build steps.

In most cases, using ES5 syntax to develop Gutenberg blocks is very convenient. However, when our code becomes very large, using ESNext syntax can reduce our code volume and make our code easier to maintain.

The new version of @wordpress/scripts includes webpack and Babel configurations, which means we can conveniently develop Gutenberg blocks without having to configure webpack or Babel ourselves.

How to Use @wordpress/scripts

First, we need to install the @wordpress/scripts package:

npm install --save-dev @wordpress/scripts

Then, we modify package.json and add the following two configuration lines.

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

When running the script above, wp-scripts will look for the src/index.js file and output the compiled code to build/index.js. After setting it up, the process for developing Gutenberg blocks is as follows:

  1. Install dependencies: npm install
  2. Start development build: npm start
  3. Develop and test
  4. Create production build: npm run build

If you want to experience this tool, you can open any example in the Gutenberg example code and use the tool above for development and building.

The role of @wordpress/scripts is to provide us with a zero-configuration, out-of-the-box Gutenberg block compilation tool to help us quickly carry out Gutenberg block development. Of course, if we need more complex configurations, we can completely achieve them through custom webpack and Babel configurations.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *