this is an application host that hosts and connects a local component called Counter and a micro-application called nav that contains a Header component that reflects and resets the counter as if it were a shopping cart
if you want to see this application running, please click on the following links
screen-recording-2023-01-23-at-32150-am_13lyLy1s.mp4
the testing running in cypress with the following command:
$ ./node_modules/.bin/cypress open
this application was build with:
NodeJs: v18.2.0
please use the package manager yarn to install the host.
$ yarn install
to run the app in a development environment
$ yarn start
this application was created with a host and nav
create an application with module federation run this command
$ npx create-mf-app
? Pick the name of your app: mf-host-simple-counter
? Project Type: Application
? Port number: 3000
? Framework: react
? Language: javascript
? CSS: Tailwind
add this configuration in webpack.config.js file for ModuleFederationPlugin
remotes: {
nav: 'mf_simple_nav@http://localhost:3001/remoteEntry.js',
},
create a component Counter.jsx
import React from 'react';
const Counter = ({count, handleBtn}) => {
return (
<div className="border-2 p-2 mt-2">
<div>Name: mf-host-simple-counter</div>
<div>Counter: {count}</div>
<button
onClick={handleBtn}
className="bg-indigo-800 font-bold text-white rounded py-2 px-4">
Add to Cart
</button>
</div>
);
};
export default Counter;
import component Counter and Header in App.jsx, connect with a hook useState
import React, {useCallback, useState} from 'react';
import ReactDOM from 'react-dom';
import Header from 'nav/Header'; // App running in port 3001
import Counter from './Counter';
import './index.scss';
const App = () => {
const [count, setCount] = useState(0);
const handleBtn = () => {
setCount(count => count + 1);
};
const setClear = () => {
setCount(0);
};
return (
<div className="mt-10 text-3xl mx-auto max-w-6xl">
<Header count={count} onClear={setClear} />
<Counter count={count} handleBtn={handleBtn} />
</div>
);
};
Use the hook useCallback for optimizing app
import React, {useCallback, useState} from 'react';
import ReactDOM from 'react-dom';
import Header from 'nav/Header';
import Counter from './Counter';
import './index.scss';
const App = () => {
const [count, setCount] = useState(0);
const handleBtn = useCallback(() => {
setCount(count => count + 1);
}, [setCount]);
const setClear = useCallback(() => {
setCount(0);
}, []);
return (
<div className="mt-10 text-3xl mx-auto max-w-6xl">
{Header && <Header count={count} onClear={setClear} />}
<Counter count={count} handleBtn={handleBtn} />
</div>
);
};