Skip to content

Instantly share code, notes, and snippets.

@ahmadawais
Created February 19, 2018 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadawais/d6e0f6ea76e075bbb2fa9bafb664beeb to your computer and use it in GitHub Desktop.
Save ahmadawais/d6e0f6ea76e075bbb2fa9bafb664beeb to your computer and use it in GitHub Desktop.
WP: Basic Block Plugin with Minimum webpack Config for WordPress Block Plugin with JSX
{
"presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 Firefox versions",
"last 2 Safari versions",
"last 2 iOS versions",
"last 1 Android version",
"last 1 ChromeAndroid version",
"ie 11"
]
}
}
]
],
"plugins": [
[
"transform-react-jsx",
{
"pragma": "wp.element.createElement"
}
]
]
}
**.DS_Store*
node_modules
package-lock.json

Basic Block WordPress Plugin

This plugin has a minimum webpack Config for WordPress Block Plugin with JSX.

basic-block
├── basic-block.php — Plugin base file.
├── block.build.js — Block's code file built via webpack/
├── block.js — Block's code source file.
├── package.json — The npm scripts are defined here.
└── webpack.config.js — The webpack configuration file.

🔥 Getting Started!

Read the files explained above. All of the files have extensive inline documentation. All you have to do is following:

  • Open up your favorite terminal app.
  • Makes sure NodeJS and NPM are installed by running node -v or npm -v to check their versions.
  • Access this directory cd /local_WordPress_Install/wp-content/plugins/basic-block/
  • Install npm dependencies by running npm install or sudo npm install
  • For building the block.js you can use run npm scripts.
    • To watch and build run npm run dev
    • To build for production run npm run build
<?php
/**
* Plugin Name: Basic Block
* Description: A basic WordPress block plugin.
* Plugin URI: https://AhmadAwais.com/
* Author URI: https://AhmadAwais.com/
* Version: 1.0.0
* License: GPL2+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*
* @package BBLK
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Enqueue Gutenberg block assets for backend editor.
*
* `wp-blocks`: includes block type registration and related functions.
* `wp-element`: includes the WordPress Element abstraction for describing the structure of your blocks.
* `wp-i18n`: To internationalize the block's text.
*
* @since 1.0.0
*/
function bblk_editor_assets() {
// Scripts.
wp_enqueue_script(
'bblk-js', // Basic Block JS.
plugins_url( '/block.build.js', __FILE__ ), // The block.build.js: We register the block here. Built with webpack.
array( 'wp-blocks', 'wp-element', 'wp-i18n') // Dependencies, defined above.
);
register_block_type( 'bblk/basic-block', array(
'editor_script' => 'bblk-js',
) );
} // End function bblk_editor_assets().
// Hook: Editor assets.
add_action( 'init', 'bblk_editor_assets' );
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
/**
* BLOCK: Basic with ESNext
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
var __ = wp.i18n.__; // Import __() from wp.i18n
var registerBlockType = wp.blocks.registerBlockType; // Import registerBlockType() from wp.blocks
/**
* Register Basic Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made available as an option to any
* editor interface where blocks are implemented.
*
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType('bblk/basic-block', {
// Block name. Block names must be a string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __('Basic Block'), // Block title.
icon: 'wordpress', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [__('Basic Block'), __('Example Block')],
// The "edit" property must be a valid function.
edit: function edit(props) {
// Creates a <p class='wp-block-bblk-basic-block'></p>.
return wp.element.createElement(
'p',
{ className: props.className },
'Hello from the editor.'
);
},
// The "save" property must be specified and must be a valid function.
save: function save() {
return wp.element.createElement(
'p',
null,
'Hello from the frontend.'
);
}
});
/***/ })
/******/ ]);
/**
* BLOCK: Basic with ESNext
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
/**
* Register Basic Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made available as an option to any
* editor interface where blocks are implemented.
*
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType( 'bblk/basic-block', {
// Block name. Block names must be a string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __( 'Basic Block' ), // Block title.
icon: 'wordpress', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [ __( 'Basic Block' ), __( 'Example Block' ) ],
// The "edit" property must be a valid function.
edit: props => {
// Creates a <p class='wp-block-bblk-basic-block'></p>.
return <p className={ props.className }>Hello from the editor.</p>;
},
// The "save" property must be specified and must be a valid function.
save: () => {
return <p>Hello from the frontend.</p>;
},
} );
{
"name": "basic-block",
"version": "1.0.0",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.3",
"webpack": "^3.11.0"
},
"scripts": {
"build": "cross-env BABEL_ENV=default NODE_ENV=production webpack",
"dev": "cross-env BABEL_ENV=default webpack --watch"
}
}
/**
* Minimum webpack Config for WordPress Block Plugin
*
* webpack basics — If you are new the webpack here's all you need to know:
* 1. webpack is a module bundler. It bundles different JS modules together.
* 2. webpack needs and entry point and an ouput to process file(s) and bundle them.
* 3. By default webpack only understands JavaScript but Loaders enable webpack to
* process more than just JavaScript files.
* 4. In the file below you will find an entry point, an ouput, and a babel-loader
* that tests all .js files excluding the ones in node_modules to process the
* modern JavaScript and make it compatible with older browsers i.e. it converts the
* code written witten with modern JavaScript (new standards of JavaScript) into old
* JavaScript through a Babel loader.
*
* Instructions: How to build or develop with this Webpack config:
* 1. In the command line browse the folder `02-basic-esnext` where
* this `webpack.config.js` file is present.
* 2. Run the `npm run dev` or `npm run build` for development or
* production respectively.
* 3. To read what these NPM Scripts do, read the `package.json` file.
*
* @link webpack https://webpack.js.org/
* @link webpack concepts https://webpack.js.org/concepts/
* @author Ahmad Awais https://github.com/ahmadawais
* @since 1.0.0
*/
module.exports = {
// Entry.
entry: "./block.js", // Import all JavaScript dependencies in this file.
// Output.
output: {
path: __dirname, // Path to produce the output. Set to the current directory.
filename: "block.build.js" // Filename of the file that webpack builds.
},
// Loaders.
// The configuration below has defined a rules property for a single module with
// two required properties: test and use. This tells webpack's compiler the following:
// "Hey webpack compiler, when you come across a '.js' or '.jsx' file inside of a
// require()/import statement, use the babel-loader to transform it before you add
// it to the bundle."
module: {
rules: [
{
test: /\.(js|jsx)$/, // Identifies which file or files should be transformed.
use: { loader: "babel-loader" }, // Babel loader to transpile modern JavaScript.
exclude: /(node_modules|bower_components)/ // JavaScript files to be ignored.
}
]
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment