npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mextblock

v1.1.5

Published

React components for MEXT federation modules

Downloads

5

Readme

MextBlock

React components for MEXT federation modules - Load and use micro-frontends as React components without republishing.

Installation

npm install mextblock
# or
yarn add mextblock

Quick Start

Basic Usage (Generic API)

import React from 'react';
import { Block } from 'mextblock';

function App() {
  return (
    <div>
      <h1>My App</h1>
      <Block 
        blockId="507f1f77bcf86cd799439011" 
        props={{
          title: "Hello World",
          theme: "dark"
        }}
      />
    </div>
  );
}

Named Components (Preferred API)

import React from 'react';
import { VirtualGame, ThreeScene } from 'mextblock';

function App() {
  return (
    <div>
      <h1>Gaming Dashboard</h1>
      
      <VirtualGame 
        props={{
          level: 1,
          playerName: "John"
        }}
      />
      
      <ThreeScene 
        props={{
          backgroundColor: "#000000",
          cameraPosition: [0, 0, 5]
        }}
      />
    </div>
  );
}

API Reference

<Block> Component

Generic component that loads any federation module by block ID.

interface BlockProps {
  blockId: string;              // Required: The block ID to load
  props?: any;                  // Props to pass to the federation module
  onLoad?: () => void;          // Callback when module loads successfully
  onError?: (error: Error) => void;  // Callback when loading fails
  fallback?: React.ReactNode;   // Custom loading component
  className?: string;           // CSS class name
  style?: React.CSSProperties;  // Inline styles
}

Example:

<Block
  blockId="507f1f77bcf86cd799439011"
  props={{ message: "Hello" }}
  onLoad={() => console.log('Loaded!')}
  onError={(error) => console.error('Failed:', error)}
  fallback={<div>Loading...</div>}
  className="my-block"
  style={{ width: '100%', height: '400px' }}
/>

Named Components

Named components are auto-generated from the server registry. They provide a cleaner API:

interface NamedBlockProps {
  props?: any;                  // Props to pass to the federation module
  onLoad?: () => void;          // Callback when module loads successfully
  onError?: (error: Error) => void;  // Callback when loading fails
  fallback?: React.ReactNode;   // Custom loading component
  className?: string;           // CSS class name
  style?: React.CSSProperties;  // Inline styles
}

Available Named Components:

  • VirtualGame - Virtual reality game component
  • ThreeScene - 3D scene renderer
  • Chart - Data visualization charts
  • Form - Dynamic form builder
  • VideoPlayer - Video player component
  • CodeEditor - Code editor with syntax highlighting
  • ImageGallery - Image gallery component
  • AnalyticsDashboard - Analytics dashboard

Configuration

Configure the package to point to your MEXT server:

import { configure } from 'mextblock';

// Configure once at the start of your app
configure({
  serverUrl: 'https://your-mext-server.com',
  enableLogging: true
});

Advanced Usage

Creating Custom Named Components

import { createNamedBlock } from 'mextblock';

// Create a custom component that maps to a specific block
export const MyCustomComponent = createNamedBlock('MyCustomComponent');

// Use it in your app
<MyCustomComponent props={{ customProp: "value" }} />

Registry Management

import { blockRegistry } from 'mextblock';

// Get all available components
const components = await blockRegistry.getAvailableComponents();
console.log('Available:', components);

// Get block ID for a component name
const blockId = await blockRegistry.getBlockId('VirtualGame');
console.log('VirtualGame Block ID:', blockId);

// Get component metadata
const info = await blockRegistry.getComponentInfo('VirtualGame');
console.log('Component info:', info);

Federation Loader

import { federationLoader } from 'mextblock';

// Manually load a federation module
const module = await federationLoader.loadModule('507f1f77bcf86cd799439011');

// Get block metadata
const metadata = await federationLoader.getBlockMetadata('507f1f77bcf86cd799439011');

// Clear cache
federationLoader.clearCache();

Federation Module Requirements

Your federation modules must export a mount function:

// In your federation module (webpack federated)
export function mount(container: HTMLElement, props?: any): void | (() => void) {
  // Mount your React component or vanilla JS
  const root = ReactDOM.createRoot(container);
  root.render(<YourComponent {...props} />);
  
  // Optional: return cleanup function
  return () => {
    root.unmount();
  };
}

// Export as default too for compatibility
export default { mount };

Development Workflow

1. Create a Block

mext-cli create "My Component"
cd block-<id>
# Make your changes
git add . && git commit -m "Add features"
git push origin main
mext-cli publish  # Automatically syncs registry!

2. Use in Your App

import { MyComponent } from 'mextblock';

<MyComponent props={{ data: "value" }} />

Note:

  • If you're on the same computer where you published: No manual sync needed! The registry was automatically updated.
  • If you're on a different computer: Run mext-cli sync first to get the latest components.

Team Development Workflow

Publishing Developer (Computer A):

mext-cli create "Shared Component"
# ... develop and publish
mext-cli publish  # ✅ Registry auto-synced locally

Other Developers (Computer B, C, D...):

# Sync to get newly published components
mext-cli sync

# Now you can use the new component
import { SharedComponent } from 'mextblock';
<SharedComponent props={{ data: "value" }} />

Error Handling

The package provides comprehensive error handling:

<Block
  blockId="invalid-id"
  onError={(error) => {
    console.error('Block failed to load:', error.message);
    // Handle error appropriately
  }}
  fallback={<div>Something went wrong...</div>}
/>

Common errors:

  • Block not found - Invalid block ID
  • Build status is not success - Block build failed
  • Federation container not found - Module export issues
  • No mount function - Module doesn't export mount function

Caching

The package automatically caches loaded modules for 5 minutes to improve performance:

import { federationLoader } from 'mextblock';

// Clear cache if needed
federationLoader.clearCache();

// Or clear specific block
federationLoader.clearCache('507f1f77bcf86cd799439011');

TypeScript Support

Full TypeScript support with proper type definitions:

import { Block, BlockProps, NamedBlockProps } from 'mextblock';

const MyComponent: React.FC<{ blockId: string }> = ({ blockId }) => {
  const handleLoad = () => console.log('Loaded!');
  const handleError = (error: Error) => console.error(error);
  
  return (
    <Block
      blockId={blockId}
      onLoad={handleLoad}
      onError={handleError}
    />
  );
};

Server Requirements

Your MEXT server must provide:

  • Block metadata endpoint: GET /api/blocks/:id
  • Registry endpoint: GET /api/blocks/registry
  • Federation modules served at: /blocks/:id/remoteEntry.js

Examples

Loading Dashboard Components

import { AnalyticsDashboard, Chart } from 'mextblock';

function Dashboard() {
  return (
    <div className="dashboard">
      <AnalyticsDashboard 
        props={{
          userId: "user123",
          timeRange: "7d"
        }}
      />
      <Chart 
        props={{
          type: "line",
          data: salesData
        }}
      />
    </div>
  );
}

Game Integration

import { VirtualGame, ThreeScene } from 'mextblock';

function GamePage() {
  return (
    <div className="game-container">
      <VirtualGame 
        props={{
          gameId: "space-invaders",
          difficulty: "medium"
        }}
        style={{ width: '100%', height: '600px' }}
      />
    </div>
  );
}

Form Builder

import { Form } from 'mextblock';

function ContactPage() {
  return (
    <Form 
      props={{
        schema: {
          fields: [
            { type: 'text', name: 'name', label: 'Name', required: true },
            { type: 'email', name: 'email', label: 'Email', required: true },
            { type: 'textarea', name: 'message', label: 'Message' }
          ]
        },
        onSubmit: (data) => console.log('Form submitted:', data)
      }}
    />
  );
}

License

MIT