How to Use React, ES6, Yarn and Webpack to Build a WordPress Plugin

If you have done any form of web development in recent times, chances are, you’ve heard of ReactJS (popularly referred to as React). In this post, we are going to dive into how to build a super basic WordPress plugin with React. We will be doing the general setup and will just display some static text in the WordPress admin page using our plugin.

The underlining ideas used and explained in the article will form the basis for most uses of React in WordPress or any other CMS or framework for that matter.

Before we start we will be defining and explaining what all the term mean (React, ES6, Yarn and Webpack). They might sound intimidating initially but once you see how they all work together it’s very easy to understand.

What is React (ReactJS)?

Whilst there are many definitions online, ReactJS is basically, is an open-source JavaScript library developed by Facebook which is used for building complex user interfaces for the web and mobile applications. It makes the building of these complex web applications more manageable and allows for code reuse.

In broad terms, most Web Applications fetch data and render it based on some form of user input. This cover over 90% of all application we build. React makes it very easy to manage all the user interactions whilst updating the data a more seamless process.

ReactJS currently has extensions which allow you to seamlessly build mobile applications (React Native) and virtual reality application (React VR). We will be using ReactJS for a web application in the case. We will cover the other uses in a future post.

There are similar frameworks such as Vue, Angular, Ember Backbone which allow you to build web applications. They all have their pros and cons. React, however, currently, has a huge following and community around it especially because the various components of React can be reused for various platforms such as Web, Mobile and VR. Additionally, one of the biggest tech companies, Facebook, is actively developing and using it in production. Using React currently is trendy.

What is ES6?

ES6, the “ES” part stands for ECMAScript and the number 6 refers to the version. ES6, which is often referred to as “Harmony” is the upcoming sixth major release of the ECMAScript language specification of which Javascript is an implementation. Essentially, what this means is that it’s the new version of Javascript programming language. Since it’s still fairly new most browsers have not fully implemented it, as such, we need a transpiler called babeljs to make it work in all browsers.

This new version of Javascript comes with features such as new scopes for variable declarations, class declarations, module loaders, generators, native promises and symbols. For an in-depth look at all the features of the new language check out the specification on github.

What is Webpack?

Webpack is a build tool that can bundle modules. It takes in a bunch of assets (ie. source, images, html, CSS, …) and turns that into combined files that are suitable for distribution.

Webpack supports advanced functionality such as hot module reloading, lazy loading, bundle splitting, hashing and source maps. Prior to the popularity of Webpack, most developers used a combination of Grunt and Gulp and a couple of manual actions to accomplish the same goal.

What is Yarn?

Yarn, which is short for Yarn Package Manager is a fast, reliable and secure dependency management. The Yarn project was started by Facebook and it’s mainly a drop-in replacement for the very popular package management tool in most web projects built with javascript called npm. Yarn has a few features missing from the npm CLI.

Yarn is fully backwards compatible with the npm package manager structure. Just like npm, is also uses the package.json and node_modules directory structure. If you are already familiar with npm, then you will more than half way familiar with yarn even if you have never heard of it.

With all the introductions out of the way, we want to the meat of this tutorial. Before we start, we want to make sure we have node and yarn all installed. Also since we will be developing a WordPress plugin it’s assumed that you have a working development environment for WordPress. We recommend Flywheel’s Local. It’s a really good dev environment to set up for WordPress. We will be covering it in a future post.

To get the updated installation instructions for installing yarn, visit the official website here.

To start, let’s create a folder that will contain everything needed for the plugin. Immediately after creating the folder, we change the working directory to that folder. Both actions can be done using the command below:

mkdir wp-react-yarn-demo && cd wp-react-yarn-demo

After this, we initialize the folder with yarn. This is done by running the yarn initialization command inside the plugin folder. You will be presented with the list of questions which allows yarn to generate the package.json file.

yarn init

Next, we install webpack and other prerequisites needed to start building. The other packages installed are webpack-dev-server and path. We will be using these packages for development.

yarn add webpack webpack-dev-server path

We can now go ahead and install all the required plugins for developing the plugin. This includes react, react-dom and webpack copy and clean plugins. All the webpack plugins allow us to build the app. Just as the name implies the react packages allow us to use react within our app.

yarn add copy-webpack-plugin
yarn add clean-webpack-plugin
yarn add webpack-hot-middleware
yarn add react 
yarn add react-dom
yarn add react-hot-loader

If you want to jump ahead and view all the final repo, it’s accessible here. Sometimes it’s easier to look at the final working demo and follow the tutorial after that.

In the next part of the post, we will be going through the important parts of the post to allow you to make the connection and see how the various files fit together. We will mostly discuss the javascript part since that is the central theme of this post. The php section, which comprises the WordPress plugin is just made up of hooks and callbacks like every other WordPress plugins.

At this point, we will go on and show the state of the package.json, which contains all the packages installed. Anytime we do yarn add,, the package manager adds that dependency to the package.json. This makes it possible for other people to run the code with ease. Additionally, we have added a custom build script that will allow us to easily generate the production version of the plugin. This is very important because, this script basically copies the compiled javascript files as well all the php files into the appropriate folder for distribution.

{
    "name": "wp-react-yarn-demo",
    "version": "1.0.0",
    "description": "A demo showing how to use react and webpack to build a WordPress plugin ",
    "main": "main.js",
    "repository": "https://github.com/wplobster/wp-react-yarn-demo",
    "author": "wplobster",
    "license": "GPL",
    "scripts": {
        "build": "NODE_ENV=production ./node_modules/.bin/webpack"
    },
    "dependencies": {
        "clean-webpack-plugin": "^0.1.16",
        "copy-webpack-plugin": "^4.0.1",
        "html-webpack-plugin": "^2.29.0",
        "path": "^0.12.7",
        "react": "^15.6.1",
        "react-dom": "^15.6.1",
        "react-hot-loader": "^1.3.1",
        "webpack": "^3.3.0",
        "webpack-dev-server": "^2.5.1",
        "webpack-hot-middleware": "^2.18.2"
    },
    "devDependencies": {
        "babel-core": "^6.25.0",
        "babel-loader": "^7.1.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "browser-sync": "^2.18.13",
        "browser-sync-webpack-plugin": "^1.2.0",
        "css-loader": "^0.28.4",
        "style-loader": "^0.18.2"
    }
}

The next file that we will be looking at is the main.js, You will notice that this file is referenced in the package.json on line 5 where we set the main entry point of the file. Basically, this file just calls our main react component called App.jsx and passes it the DOM element where the component should be rendered, a div with the id called “root”. This div is actually placed in the wp-react-yarn-demo-admin.php file which is then called when the plugin is initialized in the main plugin file. That is basically how the who setup works together.

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../components/App.jsx';

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

Let’s give a little bit more clarification on the App.jsx, that component file which is the meat of the application is where the react components will live. In this case, we are just displaying the text ‘This page is rendered in React’. Basically, jsx is a javascript preprocessor that adds XML syntax to JavaScript. Using JSX with React allows you to write less code and presents your code in a more declarative and elegant manner.

//App.jsx
import React from 'react';

export default class App extends React.Component {
    render() {
        return (
            <div style={{textAlign: 'center'}}>
                <h1>This page is rendered using React!</h1>
            </div>
        );
    }
}

The last detail we will be going into is setting up the build, this is done in the webpack.config.js file. This is where it all comes together. This file instructs webpack to generate the production ready version of the plugin which includes php, javascript and css. The Javascript and JSX are compiles and the php files are copied over. This way, the source of the builds are stored separate from the distributed files.

    webpackConfig.plugins.push(
        // Copy files and directories in webpack
        new CopyWebpackPlugin([{
                from: path.resolve(__dirname, 'src/php') + '/**',
                to: buildFolder
            },
            {
                from: path.resolve(__dirname, 'src/wp-react-yarn-demo.php'),
                to: buildFolder
            },
        ], {
            // copy all files not just unmodified files
            copyUnmodified: true
        })
    );

Once we have built the plugin, we go to our WordPress test server and install the plugin and test it out. And as you can see from the screenshot below, the plugin works great, at least for the basic task that it’s performing.

In conclusion, we covered the basics and underlying ideas behind building a WordPress plugin in ReactJS. In subsequent tutorials, we will be going into more details on this subject. If you enjoyed reading this post feel free to leave a comment of questions. Go ahead and clone the repo and play around with the code.

How to Use React, ES6, Yarn and Webpack to Build a WordPress Plugin
3.3 (65.71%) 7 votes