🛠 Tooling

Constants

Global values for affecting output bundles

There are a few globally accessible variables which you can access, which are defined via Webpack's DefinePlugin

From Webpack configuration docs:

The DefinePlugin replaces variables in your code with other values or expressions at compile time. This can be useful for allowing different behavior between development builds and production builds. If you perform logging in your development build but not in the production build you might use a global constant to determine whether logging takes place. That's where DefinePlugin shines, set it and forget it rules for development and production builds.

The following variables are available:

  • process.devtrue or false, depending on whether this bundle is targetting at dev mode or not.
  • process.admin - true or false, depending on whether this bundle is used for the admin editor (Gutenberg) or on the frontend. Useful for rendering blocks for better editing experience.
  • process.themePath - The relative URI pointing to the theme directory. Useful for calculating the location of assets. Note that there is NO trailing slash.

process.admin Example

blocks/fancy/my-block.tsx
export default defineBlock('my-block', () => {
  if (process.admin) {
    return <FancyEditor />
  } else {
    return <ContentDisplay />
  }
})

When the admin bundle is compiled, it'll look something like this:

admin.min.js
export default defineBlock('my-block', () => {
  return <FancyEditor />
})

When the public facing frontend bundle is compiled though, it'll look something like this:

admin.min.js
export default defineBlock('my-block', () => {
  return <ContentDisplay />
})

It's useful for detecting the runtime conditions, yes, but it's also great for reducing bundle sizes — we can include additional editing functionality without worrying about bloating the public frontend.

process.themePath example

A common requirement is getting the URL of a public asset held within the theme. This is where process.themePath comes in.

For example:

const imagePath = `${process.themePath}/assets/images/some-image.png`
// Resolves to /wp-content/themes/[theme-name]/assets/images/some-image.png