mextblock
v1.1.5
Published
React components for MEXT federation modules
Downloads
5
Maintainers
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 mextblockQuick 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 componentThreeScene- 3D scene rendererChart- Data visualization chartsForm- Dynamic form builderVideoPlayer- Video player componentCodeEditor- Code editor with syntax highlightingImageGallery- Image gallery componentAnalyticsDashboard- 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 syncfirst 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 locallyOther 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 IDBuild status is not success- Block build failedFederation container not found- Module export issuesNo 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
