Building and Deploying a Micro-Frontend
Outline the steps required to build a specific micro-frontend and deploy it independently from other micro-frontends.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
This is the entry point of a React micro-frontend app where the 'App' component is the root component of the micro-frontend. This code mounts the React app to an HTML element with the id 'root'.
import { registerMicroApp, start } from 'qiankun';
// Define the micro-frontend
registerMicroApp({
name: 'micro-frontend-name',
entry: '//localhost:3000',
container: '#micro-frontend-container',
activeRule: '/your-active-rule',
});
start();
This code uses the 'qiankun' library to register a micro-frontend and specify its entry URL, container element, and the route under which it should be activated. Then, it starts the micro-frontend integration.
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the React app build
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Micro-frontend is running at http://localhost:${port}/`);
});
This is a straightforward Express server that serves a production build of the micro-frontend. It listens on port 3000 or another port specified by the PORT environment variable.
import { defineConfig } from 'vite';
export default defineConfig({
// Define configuration specific to micro-frontends
build: {
outDir: 'dist',
rollupOptions: {
// Ensure we're properly including/excluding dependencies
external: ['react', 'react-dom'],
output: {
format: 'es',
// Replace 'my-micro-frontend' with the actual name
entryFileNames: `my-micro-frontend.js`,
},
},
},
});
This code provides an example configuration for a build tool like Vite, specifying build output directory and Rollup options such as module format and filename for the micro-frontend entry file.
// Deployment script
const { exec } = require('child_process');
const path = require('path');
// Building the micro-frontend
exec('npm run build', { cwd: path.resolve(__dirname, 'micro-frontend-directory') }, (error) => {
if (error) {
console.error('Error during build:', error);
return;
}
console.log('Build completed successfully.');
// You could integrate with any deployment services or custom scripts here
// For example, code to deploy to AWS S3 could be placed here.
});
This node script automates the build process using `npm run build`. After build completion, it could integrate with a deployment service or custom deployment scripts to deploy the built micro-frontend.