felipe.lavin.blog

On making stuff with code. And making code to do stuff.

Simple React builds for WordPress with Symfony’s Webpack Encore

Symfony’s Webpack Encore (docs) makes it quite easy to build your JS apps. It’s a nicer interface for the actual Webpack config, so you can also extend and customize your config to fit any use case that’s supported by webpack.

One of the cool things I’ve done with it is using it for building React apps that use WordPress code editor components for my own admin tools.

Here’s how you can use it.

Configure JS dependencies

For a bare-bones setup you will need to add the following dependencies:

npm install --save-dev @symfony/wepack-encore @wordpress/babel-preset-default @wordpress/dependency-extraction-webpack-plugin

I’ll explain each of them:

  • @symfony/webpack-encore provides a simple interface for configuring Webpack; it will also pull all its required dependencies.
  • @wordpress/babel-preset-default will provide a standard setup for js compilation, like enable JSX and more to fit into WordPress.
  • @wordpress/dependency-extraction-webpack-plugin externalizes dependencies that are available on WordPress (like @wordpress/element and @wordpress/components) to use those versions (don’t duplicate them).

After installing, you need to create a .babelrc file with the following contents:

{
	"presets": [ "@wordpress/babel-preset-default" ]
}

Configure Webpack

This is where Encore comes in. Instead of the super-verbose config that you would need here, you just need something like this on your webpack.config.js file:

const Encore = require( '@symfony/webpack-encore' );
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );

Encore.setOutputPath( 'assets/dist' )
	.setPublicPath( 'wp-content/plugins/my-awesome-plugin/assets/dist' )
	.setManifestKeyPrefix( '' )
	.enableSingleRuntimeChunk()
	.addPlugin( new DependencyExtractionWebpackPlugin() )
	.addEntry( 'admin', './assets/src/js/admin.js' )

const config =  Encore.getWebpackConfig();
module.exports = config;

You’ll need to adjust the paths and you’ll probably want to take a look at some of Encore’s configuration options.

DependencyExtractionPlugin will generate an .asset.php file for each entry point; admin.asset.php on this example. That file will contain the name of the WordPress javascript dependencies that you have declared on your components.

Keeping that in mind, then you will need to register/enqueue the required scripts on the desired pages, using WordPress’ wp_enqueue_script() — you can check Queulat’s Webpack Asset Loader helper for a simple integration (I’ll be posting an example of this soon).

With this setup you’ll be able to use any of WordPress components such as buttons, modals, focal point picker, etc.