• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar
  • Home
  • Projects
  • Products
  • Themes
  • Tools
  • Request for Quote

Vengala Vinay

Having 12+ Years of Experience in Software Development

  • Home
  • WordPress
  • PHP
    • Codeigniter
  • Django
  • Magento
  • Selenium
  • Server
Home » Step-by-Step Guide to building a custom automated performance diagnostic log block for Gutenberg using Vue micro-frontends

Step-by-Step Guide to building a custom automated performance diagnostic log block for Gutenberg using Vue micro-frontends

Project Setup: Vue Micro-Frontend and WordPress Integration

This guide details the creation of a custom Gutenberg block that leverages a Vue.js micro-frontend to provide automated performance diagnostics. We’ll focus on a practical, step-by-step approach, assuming a basic understanding of WordPress development and modern JavaScript frameworks.

Our micro-frontend will be a self-contained Vue application responsible for fetching and displaying performance metrics. This application will be embedded within a custom WordPress block. We’ll use a build process that compiles the Vue app into a JavaScript file that WordPress can enqueue.

Vue Micro-Frontend Development

First, let’s set up the Vue.js application. We’ll use Vue CLI for a streamlined development experience. If you don’t have it installed, run: npm install -g @vue/cli.

Create a new Vue project for our micro-frontend:

vue create performance-diagnostic-app
cd performance-diagnostic-app
npm install axios

Inside src/App.vue, we’ll define the basic structure for our diagnostic tool. For this example, we’ll simulate fetching performance data. In a real-world scenario, this would involve API calls to a backend service or directly to WordPress REST API endpoints.

<template>
  <div id="performance-diagnostic-app">
    <h3>Performance Diagnostics</h3>
    <div v-if="loading">Loading diagnostics...</div>
    <div v-else-if="error" class="error">Error: {{ error }}</div>
    <div v-else>
      <p><strong>Page Load Time:</strong> {{ metrics.loadTime }}ms</p>
      <p><strong>Server Response Time:</strong> {{ metrics.responseTime }}ms</p>
      <p><strong>JavaScript Errors:</strong> {{ metrics.jsErrors }}</p>
      <button @click="runDiagnostics">Refresh Diagnostics</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  data() {
    return {
      loading: true,
      error: null,
      metrics: {
        loadTime: 0,
        responseTime: 0,
        jsErrors: 0,
      },
    };
  },
  methods: {
    async fetchMetrics() {
      this.loading = true;
      this.error = null;
      try {
        // Simulate API call
        await new Promise(resolve => setTimeout(resolve, 1000));
        this.metrics = {
          loadTime: Math.floor(Math.random() * 2000) + 500, // 500-2500ms
          responseTime: Math.floor(Math.random() * 500) + 50, // 50-550ms
          jsErrors: Math.floor(Math.random() * 5), // 0-4 errors
        };
      } catch (err) {
        this.error = 'Failed to fetch performance metrics.';
        console.error(err);
      } finally {
        this.loading = false;
      }
    },
    runDiagnostics() {
      this.fetchMetrics();
    }
  },
  mounted() {
    this.fetchMetrics();
  },
};
</script>

<style scoped>
#performance-diagnostic-app {
  border: 1px solid #ccc;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #f9f9f9;
}
.error {
  color: red;
  font-weight: bold;
}
button {
  margin-top: 10px;
  padding: 8px 12px;
  cursor: pointer;
}
</style>

Next, we need to configure Vue CLI to build the application as a standalone JavaScript file suitable for inclusion in WordPress. In the performance-diagnostic-app directory, create a vue.config.js file:

module.exports = {
  publicPath: '/', // Or a specific path if you're deploying to a subdirectory
  configureWebpack: {
    output: {
      filename: 'performance-diagnostic-app.js', // Output filename
    },
    // If you need to expose Vue globally for WordPress to interact with,
    // you might need to adjust this. For a simple embed, this is often not needed.
    // externals: {
    //   vue: 'Vue'
    // }
  },
  // Disable CSS extraction to keep everything in one JS file for simplicity
  css: {
    extract: false,
  },
};

Now, build the Vue application:

npm run build

This will generate a performance-diagnostic-app.js file in the dist folder. This is the JavaScript bundle we’ll enqueue in WordPress.

WordPress Plugin and Gutenberg Block Development

We’ll create a simple WordPress plugin to house our Gutenberg block. Navigate to your WordPress installation’s wp-content/plugins/ directory and create a new folder, e.g., custom-performance-block.

Inside this folder, create the main plugin file, custom-performance-block.php:

<?php
/**
 * Plugin Name: Custom Performance Diagnostic Block
 * Description: Adds a Gutenberg block with a Vue.js micro-frontend for performance diagnostics.
 * Version: 1.0.0
 * Author: Your Name
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

/**
 * Enqueue block assets.
 */
function custom_performance_block_enqueue_assets() {
    // Enqueue the Vue micro-frontend JavaScript.
    // Make sure to copy the 'performance-diagnostic-app.js' from your Vue project's 'dist' folder
    // into your plugin's 'assets/js' directory.
    wp_enqueue_script(
        'performance-diagnostic-app-js',
        plugin_dir_url( __FILE__ ) . 'assets/js/performance-diagnostic-app.js',
        array(), // Dependencies, if any. Vue might be a dependency if not bundled.
        '1.0.0',
        true // Load in footer
    );

    // Enqueue the block editor JavaScript and CSS.
    $asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php');

    wp_enqueue_script(
        'custom-performance-block-editor-script',
        plugin_dir_url( __FILE__ ) . 'build/index.js',
        $asset_file['dependencies'],
        $asset_file['version']
    );

    // Enqueue block editor CSS (optional, for editor-specific styles).
    wp_enqueue_style(
        'custom-performance-block-editor-style',
        plugin_dir_url( __FILE__ ) . 'build/index.css',
        array(),
        $asset_file['version']
    );
}
add_action( 'enqueue_block_editor_assets', 'custom_performance_block_enqueue_assets' );

/**
 * Register the Gutenberg block.
 */
function custom_performance_block_register_block() {
    register_block_type( __DIR__ );
}
add_action( 'init', 'custom_performance_block_register_block' );

/**
 * Enqueue block assets for the frontend.
 * This is crucial for the Vue app to render on the actual website.
 */
function custom_performance_block_frontend_assets() {
    // Enqueue the Vue micro-frontend JavaScript on the frontend.
    wp_enqueue_script(
        'performance-diagnostic-app-frontend-js',
        plugin_dir_url( __FILE__ ) . 'assets/js/performance-diagnostic-app.js',
        array(), // Dependencies
        '1.0.0',
        true // Load in footer
    );

    // You might need to enqueue Vue.js itself on the frontend if your micro-frontend
    // doesn't bundle it and expects a global Vue instance.
    // wp_enqueue_script('vue', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js', array(), '2.6.14', true);
}
add_action( 'wp_enqueue_scripts', 'custom_performance_block_frontend_assets' );

Create the following directory structure within your plugin folder:

custom-performance-block/
├── build/
│   ├── index.js
│   ├── index.asset.php
│   └── index.css
├── assets/
│   └── js/
│       └── performance-diagnostic-app.js
└── custom-performance-block.php

Copy the performance-diagnostic-app.js file from your Vue project’s dist folder into custom-performance-block/assets/js/.

Now, let’s create the Gutenberg block registration and editor-side JavaScript. We’ll use the WordPress Script Dependencies API. First, install the necessary development dependencies for Gutenberg block development:

cd custom-performance-block
npm init -y
npm install @wordpress/scripts --save-dev

Add a build script to your package.json:

{
  "name": "custom-performance-block",
  "version": "1.0.0",
  "description": "",
  "main": "build/index.js",
  "scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@wordpress/scripts": "^26.10.0"
  }
}

Create a src directory within your plugin folder and add an index.js file for your block’s editor logic:

import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';

// Import the Vue micro-frontend component.
// Note: We are not directly importing the Vue component here.
// Instead, we'll use a placeholder div in the editor and rely on the enqueued script
// to mount the Vue app to that div on the frontend and potentially in the editor.

// For the editor, we'll render a simple placeholder. The actual Vue app
// will be mounted to this element when the page loads in the editor.
const Edit = () => {
    return (
        <div>
            <p>{ __('Performance Diagnostic Tool (Editor Preview)', 'custom-performance-block') }</p>
            <div id="performance-diagnostic-app-editor-mount"></div>
        </div>
    );
};

// For the frontend, we'll render a placeholder div. The Vue app will be
// mounted to this element by the enqueued script.
const Save = () => {
    return (
        <div id="performance-diagnostic-app-frontend-mount"></div>
    );
};

registerBlockType('custom-performance-block/diagnostic-tool', {
    title: __('Performance Diagnostic Tool', 'custom-performance-block'),
    icon: 'chart-bar', // Choose an appropriate icon
    category: 'widgets', // Or 'design', 'plugins', etc.
    attributes: {
        // Define any attributes if your block needs to store data.
        // For this micro-frontend approach, we might not need attributes
        // if the Vue app fetches its own data.
    },
    edit: Edit,
    save: Save,
});

Run the build command to compile your block editor JavaScript and CSS:

npm run build

This will create the build/index.js, build/index.css, and build/index.asset.php files. The index.asset.php file is crucial as it lists the WordPress script dependencies required by your block.

Integrating Vue App with WordPress Block

The key challenge is to make the Vue application mount itself correctly within the Gutenberg block’s context, both in the editor and on the frontend. Since our Vue app is built as a standalone script, we need to tell it where to mount.

Modify your Vue app’s src/main.js (or create it if it doesn’t exist) to accept a mount point ID. This allows us to dynamically specify where the Vue app should render.

import { createApp } from 'vue';
import App from './App.vue';

// Function to initialize the Vue app
function initializeVueApp(mountElementId) {
  const mountElement = document.getElementById(mountElementId);
  if (mountElement) {
    const app = createApp(App);
    // If your Vue app needs to interact with WordPress data or global variables,
    // you can pass them here. For example:
    // app.config.globalProperties.wpData = window.myWpData;
    app.mount(mountElement);
    return app; // Return the app instance if needed
  } else {
    console.error(`Mount element with ID "${mountElementId}" not found.`);
    return null;
  }
}

// Export the function so it can be called from WordPress
export { initializeVueApp };

// Optional: Auto-initialize for standalone testing if needed
// if (process.env.NODE_ENV !== 'production') {
//   document.addEventListener('DOMContentLoaded', () => {
//     initializeVueApp('performance-diagnostic-app-mount'); // Default mount ID for testing
//   });
// }

Update your Vue build configuration (vue.config.js) to ensure the output is a library that exports the initialization function:

module.exports = {
  publicPath: '/',
  configureWebpack: {
    output: {
      filename: 'performance-diagnostic-app.js',
      library: {
        name: 'performanceDiagnosticApp', // Global variable name
        type: 'var', // Or 'window', 'umd', etc.
      },
      libraryExport: 'initializeVueApp', // Export the specific function
    },
  },
  css: {
    extract: false,
  },
};

Rebuild your Vue app: npm run build.

Now, we need to modify our WordPress plugin’s JavaScript to call this exported function. Update custom-performance-block/src/index.js:

import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';

// Ensure the Vue app script is loaded before attempting to mount.
// The wp_enqueue_script in PHP handles this.

const Edit = () => {
    // Use useEffect to ensure the Vue app is mounted after the block is rendered in the editor.
    useEffect(() => {
        // Check if the global function exists and call it.
        // The global variable name 'performanceDiagnosticApp' is defined in vue.config.js.
        if (window.performanceDiagnosticApp && typeof window.performanceDiagnosticApp === 'function') {
            window.performanceDiagnosticApp('performance-diagnostic-app-editor-mount');
        } else {
            console.error('Performance diagnostic Vue app initialization function not found.');
        }

        // Cleanup function to unmount the Vue app when the block is removed or updated.
        return () => {
            // You would typically unmount the Vue app here if possible.
            // This requires the Vue app to expose an unmount method or for us to manage
            // the app instance. For simplicity, we'll rely on DOM re-rendering.
            // A more robust solution would involve storing the app instance.
            const mountElement = document.getElementById('performance-diagnostic-app-editor-mount');
            if (mountElement) {
                mountElement.innerHTML = ''; // Clear the content
            }
        };
    }, []); // Empty dependency array means this runs once after initial render.

    return (
        <div>
            <p>{ __('Performance Diagnostic Tool (Editor Preview)', 'custom-performance-block') }</p>
            <div id="performance-diagnostic-app-editor-mount"></div>
        </div>
    );
};

const Save = () => {
    // The 'Save' component returns static HTML.
    // The Vue app will be mounted to this div on the frontend by the enqueued script.
    return (
        <div id="performance-diagnostic-app-frontend-mount"></div>
    );
};

registerBlockType('custom-performance-block/diagnostic-tool', {
    title: __('Performance Diagnostic Tool', 'custom-performance-block'),
    icon: 'chart-bar',
    category: 'widgets',
    attributes: {},
    edit: Edit,
    save: Save,
});

Rebuild your block editor assets: npm run build.

Finally, we need to ensure the Vue app mounts on the frontend. We can achieve this by adding a small JavaScript snippet to our main plugin file that runs on the frontend.

Modify custom-performance-block.php to include frontend initialization:


        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                // Check if the global function exists and call it.
                if (window.performanceDiagnosticApp && typeof window.performanceDiagnosticApp === 'function') {
                    window.performanceDiagnosticApp('performance-diagnostic-app-frontend-mount');
                } else {
                    console.error('Performance diagnostic Vue app initialization function not found on frontend.');
                }
            });
        </script>
        


With these steps, you have a functional Gutenberg block that embeds a Vue.js micro-frontend for performance diagnostics. The Vue app is built separately and then integrated into the WordPress plugin, allowing for independent development and deployment of the micro-frontend.

Testing and Debugging

Activate the "Custom Performance Diagnostic Block" plugin in your WordPress admin. Then, create or edit a post/page and add the "Performance Diagnostic Tool" block. You should see the editor preview render, and on the frontend, the Vue application should mount and display the simulated diagnostics.

Debugging Tips:

  • Browser Developer Tools: Use the Console tab to check for JavaScript errors. Inspect elements to ensure the correct mount points are present.
  • Vue Devtools: If you have Vue Devtools installed in your browser, you can inspect the Vue application's components and state when viewing the page in the browser (frontend).
  • WordPress Debugging: Ensure WP_DEBUG is enabled in your wp-config.php for WordPress-related errors.
  • Build Process: If the block doesn't appear or the Vue app doesn't load, double-check that both the Vue app (npm run build) and the WordPress block assets (npm run build) have been successfully built and that the generated files are in the correct locations within the plugin directory.
  • Script Dependencies: Verify that the `performance-diagnostic-app.js` is enqueued before your block's editor script. The `wp_enqueue_script` order and dependencies are critical.

This setup provides a robust foundation for building more complex micro-frontend integrations within WordPress, enabling modular development and improved maintainability.

Primary Sidebar

A little about the Author

Having 12+ Years of Experience in Software Development, Vinay is a principal software architect, senior systems engineer, and elite technical consultant. He specializes in bespoke PHP/WordPress development, high-performance Magento 2 & Shopify architectures, custom plugin/theme development from scratch, and legacy code modernization (including VB6, VB.NET, PyQt, and Crystal Reports). Known for solving complex database bottlenecks, speed optimization (Core Web Vitals), and advanced security code auditing, Vinay engineers production-ready systems designed to scale under heavy concurrent load conditions.



Chat on WhatsApp

Recent Posts

  • How to securely integrate Stripe Payment webhook endpoints into WordPress custom plugins using REST API Controllers
  • WordPress Development Recipe: High-efficiency server-side rendering for Gutenberg blocks using Named Arguments
  • Debugging Guide: Diagnosing nonce validation collisions in multi-site network environments with modern tools
  • Troubleshooting guide: Resolving memory leak spikes caused by unclosed custom database loops in online course lessons
  • WordPress Development Recipe: Secure token-based API authentication for Twilio SMS Gateway in custom plugins

Categories

  • apache (1)
  • Business & Monetization (390)
  • Centos (4)
  • Comparisons & Decision Making (55)
  • Debian (2)
  • Debugging & Troubleshooting (653)
  • Desktop Applications (14)
  • DevOps (7)
  • DevOps & Cloud Scaling (962)
  • Django (1)
  • Laravel (4)
  • Migration & Architecture (192)
  • Mobile Applications (24)
  • MySQL (1)
  • Performance & Optimization (869)
  • PHP (5)
  • PHP Development (38)
  • Plugins & Themes (244)
  • Programming Languages (9)
  • Python (20)
  • Ruby on Rails (1)
  • Security & Compliance (638)
  • SEO & Growth (492)
  • Server (23)
  • Ubuntu (9)
  • VB6 & VB.NET (8)
  • Web Applications & Frontend (19)
  • Web Assembly (Wasm) (2)
  • WordPress (22)
  • WordPress Plugin Development (321)
  • WordPress Theme Development (357)

Recent Posts

  • How to securely integrate Stripe Payment webhook endpoints into WordPress custom plugins using REST API Controllers
  • WordPress Development Recipe: High-efficiency server-side rendering for Gutenberg blocks using Named Arguments
  • Debugging Guide: Diagnosing nonce validation collisions in multi-site network environments with modern tools

Top Categories

  • DevOps & Cloud Scaling (962)
  • Performance & Optimization (869)
  • Debugging & Troubleshooting (653)
  • Security & Compliance (638)
  • SEO & Growth (492)
  • Business & Monetization (390)

Our Products

  • ERP & LMS Systems (4)
  • Directories & Marketplaces (4)
  • Healthcare Portals (3)
  • Point of Sale (POS) (2)
  • E-Commerce Engines (2)

Our Services

  • E-Commerce Development (10)
  • WordPress Development (8)
  • Python & Desktop GUI (7)
  • General Consulting (7)
  • Legacy Modernization (5)
  • Mobile App Development (4)

Copyright © 2026 · Vinay Vengala