WordPress made a rad package that sets up webpack, Babel, and all the other packages we need to run React for WordPress Blocks.
Add a new folder in the plugins folder.
wp-content/plugins/josh-coast-banner-block
Create an index.php file in that folder.
<?php
/**
* Plugin Name: Josh Coast Banner Block
* Description: A banner intended for the top of a page including the page title and description.
* Version: 1.0
* Author: Josh Coast
* Author URI: https://www.joshcoast.com/
*
* @package joshcoast
**/
if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class JoshCoastBannerBlock {
function __construct() {
add_action('init', array($this, 'adminAssets'));
}
function adminAssets() {
register_block_type(__DIR__, array(
'render_callback' => array($this, 'theHTML')
));
}
function theHTML($attributes) {
ob_start(); ?>
<div class="josh-coast-banner-block"><pre style="display: none;"><?php echo wp_json_encode($attributes) ?></pre></div>
<?php return ob_get_clean();
}
}
$joshCoastBannerBlock = new JoshCoastBannerBlock();
Add a src
directory. This directory will be where you work on all your source files. Webpack will build the files and place them all into your build
directory for you. When telling WordPress where various files are, this build
directory is where you will point to.
wp-content/plugins/josh-coast-banner-block/src
wp-content/plugins/josh-coast-banner-block/build
Initialize npm to create the package.json
file and run this with the terminal in your plugin directory.
npm init -y
Install the @wordpress/scripts
Run this with the terminal in your plugin directory.
npm install @wordpress/scripts --save-dev
Add the build and start lines ( lines 7 & 8 ) to your package.json file
{
"name": "josh-coast-banner-block",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@wordpress/scripts": "^26.2.0"
}
}
To run these new scripts, run this with the terminal in your plugin directory.
npm run start // this runs the "watch" command for active development.
npm run build // this runs the "build" command for production.
This will create/update a build directory in your plugin!