### Start the development server
Source: https://front-hub.rdstation.com.br/docs/creating-from-scratch
Navigate to the main package directory and start the application development server.
```bash
cd my-first-project/packages/main
yarn start
```
--------------------------------
### Example Application Host Configuration
Source: https://front-hub.rdstation.com.br/docs/config
A practical example of configuring routes and files for a blog comments micro frontend.
```javascript
module.exports = {
metadata: {
applicationHosts: [
{
code: 'my-blog',
routes: [
{
path: '/:category/:post-name',
files: [
'http://my-git-service.com/my-blog/controllers/posts.js',
'http://my-git-service.com/my-blog/views/posts.html',
],
},
{
path: '/pages/:id',
files: [
'http://my-git-service.com/my-blog/controllers/pages.js',
'http://my-git-service.com/my-blog/views/pages.html',
],
},
{
path: '/about/projects',
files: ['http://my-git-service.com/my-blog/public/project.html'],
},
],
},
],
},
}
```
--------------------------------
### Example .env.development file
Source: https://front-hub.rdstation.com.br/docs/environments
Defines a custom environment variable with the REACT_APP_ prefix for the development environment. This file is used when the app is started locally with 'yarn start'.
```plaintext
REACT_APP_NOT_SECRET_VALUE=qwer
```
--------------------------------
### Example: create package my-microfrontend
Source: https://front-hub.rdstation.com.br/docs/cli
Example workflow: change to the monorepo directory and run the create package command to generate a new package with all FrontHub configuration inside the packages directory.
```bash
cd my-monorepo
front-hub create package my-microfrontend
```
```text
my-monorepo/
packages/
my-microfrontend/
```
--------------------------------
### Start Fake repository
Source: https://front-hub.rdstation.com.br/docs/fake-repository
Run this command in the Micro Frontend root directory to start a local instance ready for consumption by an Application Host, typically on port 3001.
```bash
yarn fake repository
```
--------------------------------
### Basic Router setup with react-router-dom
Source: https://front-hub.rdstation.com.br/docs/routers
Shows a basic Router configuration with a User route, where all route props (match, location, history) are available to the User component. This example uses the history object directly.
```react
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route } from 'react-router-dom'
import { useHistory } from '@resultadosdigitais/front-hub/react'
// All route props (match, location and history) are available to User
function User(props) {
return
Hello {props.match.params.username}!
}
ReactDOM.render(
,
node,
)
```
--------------------------------
### Setup test file for Create React App (setupTests.js)
Source: https://front-hub.rdstation.com.br/docs/testing
Required for micro frontends not created with front-hub-cli when using Create React App. Calls the setup method from FrontHub with the front-hub config.
```javascript
import '@testing-library/jest-dom/extend-expect'
import { setup } from '@resultadosdigitais/front-hub/react/jest'
import 'jest-styled-components'
import fronthubConfig from '../front-hub.config'
setup(fronthubConfig)
```
--------------------------------
### Install FrontHub CLI via script
Source: https://front-hub.rdstation.com.br/docs/troubleshooting
Run this script to install the FrontHub CLI globally after setting up NVM to resolve permission issues.
```bash
curl -L https://front-hub.rdstation.com.br/install.sh | sudo bash
```
--------------------------------
### Initialize package with yarn
Source: https://front-hub.rdstation.com.br/docs/lib-getting-started
Starts the package configuration using yarn init.
```bash
yarn init
```
--------------------------------
### Install react-i18next
Source: https://front-hub.rdstation.com.br/docs/localization
Command to install the required dependency for React applications.
```bash
yarn add react-i18next
```
--------------------------------
### CLI commands to initialize micro frontends
Source: https://front-hub.rdstation.com.br/docs/how-it-works
Run these commands to create two independent micro frontend projects named `app1` and `app2`. The generated projects are ready to use, and you can start the development server with `yarn start`.
```bash
front-hub init app1
front-hub init app2
```
--------------------------------
### Install Auto dependencies
Source: https://front-hub.rdstation.com.br/docs/lib-releases
Install the required development dependencies for the release automation workflow.
```bash
yarn add --dev auto @auto-it/first-time-contributor
```
--------------------------------
### Install Prettier and config
Source: https://front-hub.rdstation.com.br/docs/lib-getting-started
Installs Prettier and the @resultadosdigitais/prettier-config as dev dependencies.
```bash
yarn add --dev prettier @resultadosdigitais/prettier-config
```
--------------------------------
### Run front-hub without arguments to see help
Source: https://front-hub.rdstation.com.br/docs/cli
Run `front-hub` with no arguments to display the CLI help. This is the global installation usage.
```bash
front-hub
```
--------------------------------
### Initialize a new FrontHub project
Source: https://front-hub.rdstation.com.br/docs/creating-from-scratch
Use this command to create a new FrontHub application from scratch. Ensure the front-hub-cli is installed before running.
```bash
front-hub init my-first-project
```
--------------------------------
### Install react-router-dom
Source: https://front-hub.rdstation.com.br/docs/routers
Adds the react-router-dom package to your micro frontend project. This is the first step to start using routing in FrontHub.
```bash
yarn add react-router-dom
```
--------------------------------
### Define collection and pagination headers in users.js
Source: https://front-hub.rdstation.com.br/docs/fake-api
This example shows how to define a user collection schema and implement a GET handler that reads pagination request headers and sets corresponding response headers.
```javascript
export const collection = () => {
return {
name: 'users',
schema: {
type: 'array',
minItems: 10,
maxItems: 100,
items: {
type: 'object',
properties: {
name: {
type: 'string',
faker: 'internet.userName',
},
email: {
type: 'string',
faker: 'internet.email',
},
},
required: ['user', 'email'],
},
},
}
}
export const get = (req, res, _, { db }) => {
const result = db.get('users')
const entities = result.value()
// Get info from request headers
const page = req.headers['pagination-page'] || 1
const perPage = req.headers['pagination-per-page'] || 10
const startIndex = (page - 1) * perPage
const endIndex = startIndex + perPage
const users = entities.slice(startIndex, endIndex)
const size = users.length
// Set info into response headers
res.setHeader('pagination-page', page)
res.setHeader('pagination-per-page', perPage)
res.setHeader('pagination-page-size', size)
res.setHeader('pagination-total', entities.length)
// Expose all new headers
res.setHeader('Access-Control-Expose-Headers', '*')
res.json({ users })
}
```
--------------------------------
### Example .env.staging file
Source: https://front-hub.rdstation.com.br/docs/environments
Defines a custom environment variable with the REACT_APP_ prefix for the staging environment.
```plaintext
REACT_APP_NOT_SECRET_VALUE=asdf
```
--------------------------------
### Configure multiple micro frontends in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of registering multiple versions of the same micro frontend in the configuration file.
```javascript
mfeDependencies: ['sidebar@1.0.1', 'sidebar@1.0.2']
```
--------------------------------
### Start Fake repository with custom port
Source: https://front-hub.rdstation.com.br/docs/fake-repository
Use the -p flag to specify a custom port number for the Fake repository instance.
```bash
yarn fake repository -p 3002
```
--------------------------------
### Example .env.production file
Source: https://front-hub.rdstation.com.br/docs/environments
Defines a custom environment variable with the REACT_APP_ prefix for the production environment.
```plaintext
REACT_APP_NOT_SECRET_VALUE=zxcv
```
--------------------------------
### Run front-hub via npx
Source: https://front-hub.rdstation.com.br/docs/cli
Run the CLI using npx, which comes with npm 5.2+ and higher. This avoids a global install.
```bash
npx @resultadosdigitais/front-hub-cli
```
--------------------------------
### Locale JSON Files
Source: https://front-hub.rdstation.com.br/docs/localization
Example content for English and Portuguese locale files.
```json
{
"pet": {
"salute": "Hello",
"apples": "I have {{ apples, number }} apples"
}
}
```
```json
{
"pet": {
"salute": "Olá",
"apples": "Eu tenho {{ apples, number }} maçãs"
}
}
```
--------------------------------
### Grants property example
Source: https://front-hub.rdstation.com.br/docs/authorization
Shows the grants object structure, assigning permissions to roles. Includes wildcard, negation, and inheritance examples.
```javascript
permissions: {
article: ['read', 'create', 'edit', 'delete']
},
grants: {
guest: ['article:read'],
writer: ['article:*', 'not article:delete', 'password:forgot'],
admin: ['extends writer', 'article:delete', 'user:*', 'password:*']
}
```
--------------------------------
### Fetch paginated data from client
Source: https://front-hub.rdstation.com.br/docs/fake-api
This example demonstrates how to create an API client and parse the pagination headers returned by the Fake API.
```javascript
import { client } from '@resultadosdigitais/front-hub/http'
const api = () => {
// Change 'service-name' with your Fake API name
return client.create('service-name')
}
const parseHeaders = headers => ({
getHeaderInt: key => {
const result = parseInt(headers[key], 10)
return isNaN(result) ? 0 : result
},
})
const getUsers = async () => {
const { data, headers } = await api().get('/users')
const { getHeaderInt } = parseHeaders(headers)
const pagination = {
page: getHeaderInt('pagination-page'),
perPage: getHeaderInt('pagination-per-page'),
pageSize: getHeaderInt('pagination-page-size'),
total: getHeaderInt('pagination-total'),
}
return { users: data.users, pagination }
}
```
--------------------------------
### Test microfrontend rendering
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of using the selector to verify that a microfrontend is rendered and contains the expected props and priority.
```javascript
it('renders with mfe correctly', async () => {
const { getMicrofrontendByName } = renderWithFrontHub()
const mfe = getMicrofrontendByName('the_microfrontend_name')
expect(mfe).toBeInTheDocument()
expect(mfe.props).toEqual({ your: 'prop' })
expect(mfe.priority).toEqual('medium')
})
```
--------------------------------
### Basic endpoint example in healthcheck.js
Source: https://front-hub.rdstation.com.br/docs/fake-api
A simple GET endpoint that returns a JSON response with database and redis status. This is a basic example of an endpoint.
```javascript
export const get = (req, res) => {
res.json({
database: 'ok',
redis: 'ok',
})
}
```
--------------------------------
### Connect with intlFormatting addon in src/index.js
Source: https://front-hub.rdstation.com.br/docs/connect
Example of configuring the intlFormatting addon within the Connect function. Note that this process is deprecated.
```javascript
import { Connect } from '@resultadosdigitais/front-hub/react'
import { Theme, Reset } from '@resultadosdigitais/tangram-components'
import App from './App'
export default Connect(
props => (
),
{
intlFormatting: (config, context) => {
return (value, format, lng) => {
// format and then return
return value
}
},
},
)
```
--------------------------------
### Configure version mismatch in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of a configuration where the registered version does not match the requested version.
```javascript
mfeDependencies: ['sidebar@1.0.1']
```
--------------------------------
### Configure multiple dependencies for ambiguous resolution
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of registering multiple versions without a latest tag, causing ambiguity when no version is specified.
```javascript
mfeDependencies: ['sidebar@1.0.1', 'sidebar@1.0.2', 'sidebar@1.0.3']
```
--------------------------------
### Configure Commons in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/config
Specifies the name of the installed package containing common dependencies.
```javascript
module.exports = {
commons: {
name: '@resultadosdigitais/front-hub-commons',
},
}
```
--------------------------------
### Basic Connect usage in src/index.js
Source: https://front-hub.rdstation.com.br/docs/connect
A basic example of using the Connect function to wrap an application with theme and reset components.
```javascript
import { Connect } from '@resultadosdigitais/front-hub/react'
import { Theme, Reset } from '@resultadosdigitais/tangram-components'
import App from './App'
export default Connect(props => (
))
```
--------------------------------
### Install FrontHub dependencies for CRA not ejected
Source: https://front-hub.rdstation.com.br/docs/migrating-from-cra
Run these commands in your project root to install the FrontHub core and commons packages.
```bash
yarn add @resultadosdigitais/front-hub @resultadosdigitais/front-hub-commons
```
--------------------------------
### Implement Microfrontend component with version mismatch
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of a component call requesting a version not present in the configuration.
```jsx
```
--------------------------------
### SPA routing configuration with React Router
Source: https://front-hub.rdstation.com.br/docs/routers
Example of SPA routing configuration for a microfrontend with routes for users, new user, user detail, and user groups.
```jsx
```
--------------------------------
### Configure JFrog NPM Registry
Source: https://front-hub.rdstation.com.br/docs/getting-started
Run this command to configure the JFrog registry, which is required to install FrontHub modules.
```bash
bash -c "$(curl -fsSL https://front-hub.rdstation.com.br/jfrog-setup.sh)"
```
--------------------------------
### Call multiple micro frontends in component code
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of calling different versions of a micro frontend in the component code.
```jsx
```
--------------------------------
### Custom Decimal Format
Source: https://front-hub.rdstation.com.br/docs/localization
Example of defining a custom decimal format in a locale file.
```json
{
"price": "Price: {{value, decimal}}"
}
```
--------------------------------
### Implement Microfrontend component for missing registration
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of a Microfrontend component call that fails when the dependency is not registered.
```jsx
```
--------------------------------
### Implement Microfrontend component without version
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of a component call that fails to identify a specific version when multiple are registered.
```jsx
```
--------------------------------
### Create project directory
Source: https://front-hub.rdstation.com.br/docs/lib-getting-started
Initializes a new project by creating and entering a directory named my-lib.
```bash
mkdir my-lib
cd my-lib
```
--------------------------------
### Permissions property example
Source: https://front-hub.rdstation.com.br/docs/authorization
Shows the permissions object structure, mapping a feature (article) to an array of permission kinds.
```javascript
permissions: {
article: ['read', 'create', 'edit', 'delete']
}
```
--------------------------------
### Example of enabled features array
Source: https://front-hub.rdstation.com.br/docs/feature-flag
The features function must resolve to an array containing the names of all enabled features.
```json
["whatsapp"]
```
--------------------------------
### Fix MFE not found error in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Example of an empty mfeDependencies array in front-hub.config.js that causes a 'not found' error.
```javascript
mfeDependencies: []
```
--------------------------------
### Configure Auto npm plugin for jFrog
Source: https://front-hub.rdstation.com.br/docs/lib-releases
Example configuration for the npm plugin in package.json, specifically disabling setRcToken for jFrog registries.
```json
"plugins": [
[
"npm",
{
"setRcToken": false
}
],
]
```
--------------------------------
### Jest configuration for non-Create React App (jest.config.js)
Source: https://front-hub.rdstation.com.br/docs/testing
Required for micro frontends not created with front-hub-cli and not using Create React App. Configures Jest by calling setup with the front-hub config.
```javascript
const { setup } = require('@resultadosdigitais/front-hub/react/jest')
setup(require('../front-hub.config.js'))
```
--------------------------------
### Example of chaotic git log in a development branch
Source: https://front-hub.rdstation.com.br/docs/lib-workflow
Shows a typical git log in a development branch with messy commit messages, illustrating why squash merge is enforced for history readability.
```text
7hgf8978g9... Added new slideshow feature, task #84839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
9080gf6567... Fixed in code review
gh34839843... minor fix (typo) for 3rd test
```
--------------------------------
### front-hub init command syntax
Source: https://front-hub.rdstation.com.br/docs/cli
Initializes a FrontHub project in a blank git repository. Use the -y/--yes option to run with default config. For extra configurations, use front-hub.config.js.
```bash
front-hub init [options]
```
--------------------------------
### Set Instrumentation Listeners in Application Host
Source: https://front-hub.rdstation.com.br/docs/instrumentation
Defines listeners for 'track' and 'log' events in the Application Host. The track listener receives the event object and the log listener receives the context. The example uses next() to continue the chain after processing.
```JavaScript
fronthub('instrumentation', {
track: function (event, next) {
AnalyticsService.track(event.name, event.payload)
next()
},
log: function (context, next) {
if (context.level === 'error') {
ErrorService.error(context.message, context)
} else {
LogService.info(context.message, context)
}
next()
},
})
```
--------------------------------
### Install react-app-rewired@1.6.2 for react-scripts-ts with Webpack 3
Source: https://front-hub.rdstation.com.br/docs/migrating-from-cra
Alternative react-app-rewired version when using react-scripts-ts and Webpack 3, installed as a development dependency.
```bash
yarn add react-app-rewired@1.6.2 -D
```
--------------------------------
### Test Posts with instanceMock (testing Posts component with instanceMock)
Source: https://front-hub.rdstation.com.br/docs/testing
A test example showing how to use `instanceMock` from `@resultadosdigitais/front-hub/react/jest` to mock FrontHub features in a specific test spec. It wraps the `Posts` component with `instanceMock` and `renderWithTranslation`, and reuses the same mock data across both test cases.
```javascript
import React from 'react'
import { render } from '@testing-library/react'
import {
instanceMock,
renderWithTranslation,
} from '@resultadosdigitais/front-hub/react/jest'
import Posts from '.'
const mockPosts = [
{ id: 1, title: 'Post title one' },
{ id: 2, title: 'Post title two' },
]
describe('Posts', () => {
it('should render a post with title "post title one"', () => {
const { getByText } = render(
renderWithTranslation(instanceMock()),
)
expect(getByText(/post title one/i)).toBeInTheDocument()
})
})
```
--------------------------------
### Install react-app-rewired for CRA 2.x with Webpack 4
Source: https://front-hub.rdstation.com.br/docs/migrating-from-cra
Installs react-app-rewired as a dev dependency for create-react-app 2.x applications with Webpack 4, enabling access to webpack plugins in non-ejected CRA apps.
```bash
yarn add react-app-rewired -D
```
--------------------------------
### Initialize and use the API client in React
Source: https://front-hub.rdstation.com.br/docs/fake-api
Demonstrates creating an API client instance on demand and using it within a React component's useEffect hook to fetch data.
```javascript
import { useState, useEffect } from 'react'
import { client } from '@resultadosdigitais/front-hub/http'
/**
* Put the creation of the client in a function or class
* so that it is created on demand
*/
const api = () => {
// Returns an axios instance
return client.create('service-name')
}
const App = () => {
// Give preference to userReducer to handle more complete request state,
// or use something ready-made like React Query
const [leads, setLeads] = useState([])
useEffect(() => {
api()
.get('/leads')
.then(response => {
setLeads(response.data)
})
}, [])
return (
{leads.map(lead => (
{lead.name}
))}
)
}
```
--------------------------------
### front-hub init
Source: https://front-hub.rdstation.com.br/docs/cli
Initialize a new FrontHub project in a blank git repository. This command is meant to be executed in a blank git repository; for migrating from create react app, follow the migration instructions.
```APIDOC
## front-hub init
### Description
Initialize a new FrontHub project in a blank git repository. This command is meant to be executed in a blank git repository; for migrating from create react app, follow the migration instructions.
### Usage
```
front-hub init [options]
```
### Options
- **-y**, **--yes** - Runs with default config
- **-h**, **--help** - Display help for command
### Notes
For extra configurations use the front-hub.config.js.
```
--------------------------------
### Clone and initialize an existing repository
Source: https://front-hub.rdstation.com.br/docs/creating-from-scratch
Use these commands to clone an existing Git repository and initialize the FrontHub project within it.
```bash
git clone git@github.com:YourCompany/my-first-project.git
cd my-first-project
front-hub init
```
--------------------------------
### Environment folder structure for micro frontend
Source: https://front-hub.rdstation.com.br/docs/environments
Shows the required directory layout: each micro frontend must have an 'env' folder containing .env.development, .env.staging, and .env.production files. The build command must be 'build' (not 'build:prod') in package.json.
```plaintext
Inside each own MFE folder
├── my-monorepo/
│ ├── packages/
│ └── my-microfrontend/
│ └── env/
│ └── .env.development
│ └── .env.staging
│ └── .env.production
│ └── src/
```
--------------------------------
### Use Translation in Component
Source: https://front-hub.rdstation.com.br/docs/localization
Example of importing and using the useTranslation hook within a React component.
```javascript
import React from 'react'
import { useTranslation } from 'react-i18next'
const apples = 42
const Component = () => {
const { t } = useTranslation()
return (
{t('pet.salute')}!
{t('pet.apples', { apples })}
)
}
```
--------------------------------
### Configure the API client with Axios options
Source: https://front-hub.rdstation.com.br/docs/fake-api
Shows how to pass an optional configuration object to the client.create method, which is then applied to the underlying Axios instance.
```javascript
import { client } from '@resultadosdigitais/front-hub/http'
const api = () => {
// The configuration object is of type AxiosRequestConfig
return client.create('service-name', {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': 'the_token',
},
})
}
export default api
```
--------------------------------
### front-hub create package command syntax
Source: https://front-hub.rdstation.com.br/docs/cli
Creates a package in a FrontHub project. Use -y/--yes for default config. For extra configurations, use front-hub.config.js.
```bash
front-hub create package [options] [project-directory]
```
--------------------------------
### Implement intlFormatting in Connect
Source: https://front-hub.rdstation.com.br/docs/localization
Registering the intlFormatting addon within the Connect function in the entrypoint file.
```javascript
import { Connect } from '@resultadosdigitais/front-hub/react'
const App = () =>
{t('price', { value: 123456.789 })}
export default Connect(() => , {
intlFormatting: function (config, context) {
return function (value, format, lng) {
if (format === 'decimal') {
return new Intl.NumberFormat(lng, {
style: 'currency',
currency: context.user.currency,
}).format(value)
}
return value
}
},
})
```
--------------------------------
### Configure repository for Fake repository
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Point the repository key to the local port where the fake repository is running. The application must be restarted after this change.
```javascript
repository: 'http://localhost:3001', // or another port that fake repository returned
...rest_of_configs,
```
--------------------------------
### Configure repository for Staging
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Add the repository key to the front-hub.config.js file to point to the staging URL for local development.
```javascript
repository: 'https://THE_FRONT-HUB_STAGING-URL',
...rest_of_configs,
```
--------------------------------
### front-hub fake repository command syntax
Source: https://front-hub.rdstation.com.br/docs/cli
Creates a fake FrontHub repository. Options include -p/--port (default: 3001), --paths, -pl/--parallel (default: 2), --no-cache, -d/--development, and -stg/--staging.
```bash
front-hub fake repository [options]
```
--------------------------------
### Configure Events in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/config
Sets up event listeners and emitters for communication between micro frontends.
```javascript
module.exports = {
events: {
/**
* Array containing all events to be listened on your micro frontend
*/
listeners: [],
/**
* Array containing all events to emitted from your micro frontend
*/
emitters: [],
},
}
```
--------------------------------
### Run Fake repository as development
Source: https://front-hub.rdstation.com.br/docs/fake-repository
Use the -d flag to run the Fake repository in development mode.
```bash
yarn fake repository -d
```
--------------------------------
### Run Fake repository with custom paths
Source: https://front-hub.rdstation.com.br/docs/fake-repository
Use the --paths flag to specify custom paths outside the microfrontend folder.
```bash
yarn fake repository --paths packages/mfe-a packages/mfe-b
```
--------------------------------
### front-hub
Source: https://front-hub.rdstation.com.br/docs/cli
Run the FrontHub CLI without arguments to display help information.
```APIDOC
## front-hub
### Description
Run the FrontHub CLI without arguments to display help information.
### Usage
```
front-hub
```
### Options
- **-V**, **--version** - Output the version number
- **-h**, **--help** - Display help for command
```
--------------------------------
### Run Fake repository with npx
Source: https://front-hub.rdstation.com.br/docs/fake-repository
Use npx to run the command from anywhere on your system, without being restricted to the project directory.
```bash
npx @resultadosdigitais/front-hub-cli fake repository --paths ~/monorepoA/packages/mfe-a ~/monorepoB/packages/mfe-b
```
--------------------------------
### Initialize getMicrofrontendByName
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Initialize the selector within your test component render.
```javascript
const { getMicrofrontendByName } = renderWithFrontHub()
```
--------------------------------
### Implementing a Basic Log Listener
Source: https://front-hub.rdstation.com.br/docs/instrumentation
Use the log property to listen to all logs on the Application Host.
```javascript
fronthub('instrumentation', {
log: function (context, next) {
console.log(context)
next()
},
})
```
--------------------------------
### Configure context as Promise
Source: https://front-hub.rdstation.com.br/docs/context-data
Configures the Application Host context using a Promise that resolves to the context object.
```javascript
fronthub('configure', {
repository: 'https://front-hub-repository-url.com',
context: new Promise((res, rej) => {
return res({
user: {
id: '12345',
name: 'Michael Scott',
account: {
name: 'Dunder Mifflin',
},
},
})
}),
})
```
--------------------------------
### Welcome component test boilerplate (Welcome.test.js)
Source: https://front-hub.rdstation.com.br/docs/testing
Default test file created with new apps, verifying that the Welcome component renders a heading. Uses Testing Library React's render and screen.
```javascript
import { render, screen } from '@testing-library/react'
import Welcome from './Welcome'
it('should render title', () => {
render()
expect(screen.getByRole('heading')).toBeInTheDocument()
})
```
--------------------------------
### Microfrontend errorCallback property
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
The 'errorCallback' property is a function to handle errors during the micro frontend require process. Note the typo 'erroCallback' in the example.
```jsx
{
MyCustomErrorService.error(error)
console.error(`Failed to load MFE: ${error}`)
}}
/>
```
--------------------------------
### Run fake API with front-hub CLI
Source: https://front-hub.rdstation.com.br/docs/fake-api
Use the 'front-hub fake api' command to run the fake API service. For projects not using Lerna, add '--noLerna'. Optionally specify a port with '-p'.
```bash
front-hub fake api
```
```bash
front-hub fake api --noLerna
```
```bash
front-hub fake api -p 9000
```
--------------------------------
### Run Fake repository as staging
Source: https://front-hub.rdstation.com.br/docs/fake-repository
Use the -stg flag to run the Fake repository in staging mode.
```bash
yarn fake repository -stg
```
--------------------------------
### Unlistening to events in Application Host
Source: https://front-hub.rdstation.com.br/docs/communication
The fronthub function with the 'listen' command returns an unlisten function. This example demonstrates using it to stop updating the title color when the button is clicked.
```javascript
Change Color
```
--------------------------------
### Directory structure for multiple APIs
Source: https://front-hub.rdstation.com.br/docs/fake-api
Directories must follow the 'rootDir' configuration. This structure shows where to place fake API files for each service.
```text
├── my-monorepo/
│ ├── packages/
│ └── my-microfrontend
│ └── fake-analytics-api/
│ └── dashboard.js
│ └── ...
│ └── fake-leads-api/
│ └── leads.js
│ └── ...
```
--------------------------------
### Update package.json scripts to use react-app-rewired
Source: https://front-hub.rdstation.com.br/docs/migrating-from-cra
Modifies the npm scripts in package.json to use react-app-rewired for start, build, and test. Note that the build script must explicitly set NODE_ENV=production.
```json
- "scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "NODE_ENV=production react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test"
}
```
--------------------------------
### Unlistening to events in React Micro Frontend
Source: https://front-hub.rdstation.com.br/docs/communication
The useListener hook returns an unlisten function that stops the callback from executing when called. In this example, clicking the button triggers the unlisten function to fix the title color.
```javascript
import React, { useState } from 'react'
import { useCommunication } from '@resultadosdigitais/front-hub/react'
const App = () => {
const [color, setColor] = useState('blue')
const { useListener } = useCommunication('style')
const unlisten = useListener('changeTitleColor', ({ color: newColor }) => {
setColor(newColor)
})
return (
<>
Hello Front-Hub!
>
)
}
```
--------------------------------
### Posts component using useTranslation (Posts.js)
Source: https://front-hub.rdstation.com.br/docs/testing
Shows a React component that uses the `useTranslation` hook from `react-i18next` to translate a `postsTitle` and render a list of posts. A backed example is used to return a list of Posts.
```javascript
import React from 'react';
import { useTranslation } from 'react-i18next';
export default const Posts = ({ posts }) => {
const { t } = useTranslation();
return (
{t('postsTitle')}
{
posts.length > 0 && (
{
posts.map(post =>
{post.title}
)
}
)
}
)
}
```
--------------------------------
### Configure context as async function (API call)
Source: https://front-hub.rdstation.com.br/docs/context-data
Configures the Application Host context using an async function that fetches data from an API. The returned Promise resolves to the context object.
```javascript
fronthub('configure', {
repository: 'https://front-hub-repository-url.com',
context: async () => {
return fetch('https://api-example.com/context').then(response =>
response.json(),
)
},
})
```
--------------------------------
### Emulate features in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/feature-flag
Configuration for development mode to emulate the feature service.
```javascript
module.exports = {
features: ['whatsapp'],
}
```
--------------------------------
### Using useHistory hook with Router
Source: https://front-hub.rdstation.com.br/docs/routers
Introduced in version 9, this example uses the custom useHistory hook from FrontHub to enable SPA navigation between micro frontends. All micro frontends using Router must use this hook for seamless transitions.
```react
import { useHistory } from '@resultadosdigit/front-hub/react'
import { Router, Route } from 'react-router-dom'
const Routes = () => {
const history = useHistory()
return (
)
}
```
--------------------------------
### front-hub fake api command syntax
Source: https://front-hub.rdstation.com.br/docs/cli
Creates a fake FrontHub API. Options include -L/--noLerna for repositories without lerna, and -p/--port to specify the listening port (default: 5000).
```bash
front-hub fake api [options]
```
--------------------------------
### Configure Services in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/config
Defines an array of service settings including endpoints for production.
```javascript
module.exports = {
services: [
{
name: 'service-name',
rootDir: '/fake-api',
endpoints: {
production: 'https://api.my-project.com',
},
},
],
}
```
--------------------------------
### Configure front-hub.config.js for event listeners
Source: https://front-hub.rdstation.com.br/docs/communication
Define the events your Micro Frontend needs to listen to by adding them to the listeners array in the configuration file.
```javascript
module.exports = {
events: {
listeners: ['style:changeTitleColor'],
},
}
```
--------------------------------
### Access Profiler.phases.mount and Profiler.phases.update
Source: https://front-hub.rdstation.com.br/docs/profiler
Use the phases collection to filter by mount or update phase.
```javascript
Profiler.phases.mount
Profiler.phases.update
```
--------------------------------
### Configure Application Hosts
Source: https://front-hub.rdstation.com.br/docs/config
Connects the micro frontend to an Application Host registered on FrontHub Admin.
```javascript
module.exports = {
metadata: {
applicationHosts: [
{
/**
* Code registered on FrontHub Admin. (required)
*/
code: '',
/**
* List of routes used in Application Host to load the micro frontend.
*/
routes: [
{
/**
* Rule used in Application Host routing.
*/
path: '',
/**
* List of files used to load the micro frontend.
* We recommend using the URL of the file in the
* repository to make it easier to find.
*/
files: [''],
},
],
},
],
},
}
```
--------------------------------
### Configure Micro Frontend emitters in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/communication
Add the events key to your front-hub.config.js file to register the channels and messages that a Micro Frontend is permitted to emit.
```javascript
module.exports = {
events: {
emitters: ['style:changeTitleColor'],
},
}
```
--------------------------------
### Configure application host for feature flags
Source: https://front-hub.rdstation.com.br/docs/feature-flag
Initial configuration for the application host using the fronthub function to fetch enabled features.
```javascript
fronthub('configure', {
features: ({ name /* the microfrontend name */ }) =>
fetch('/some/feature/flagger/' + name).then(response => response.json()),
})
```
--------------------------------
### Configure context as function
Source: https://front-hub.rdstation.com.br/docs/context-data
Configures the Application Host context using a function that returns the context object. The function is called to provide the context.
```javascript
fronthub('configure', {
repository: 'https://front-hub-repository-url.com',
context: () => {
return {
user: {
id: '12345',
name: 'Michael Scott',
account: {
name: 'Dunder Mifflin',
},
},
}
},
})
```
--------------------------------
### fronthub('requireMicrofrontend', ...)
Source: https://front-hub.rdstation.com.br/docs/require-microfrontend
The requireMicrofrontend command loads a micro frontend and renders it at a specified DOM element. It accepts the micro frontend name, an optional version, a hub function for rendering, and an options object.
```APIDOC
## fronthub('requireMicrofrontend', ...)
### Description
The `requireMicrofrontend` command loads a micro frontend and renders it at a specified DOM element. It accepts the micro frontend name, an optional version, a hub function for rendering, and an options object.
### Method
This is a JavaScript function call, not an HTTP endpoint.
### Signature
```
fronthub('requireMicrofrontend', microfrontendName, hubFunction, options?)
```
### Parameters
- **microfrontendName** (string) - Required - The name of the micro frontend as specified in its `package.json`. To require a fixed version, append `@THE_SEMVER_VERSION` to the name (e.g., `'YOUR_MICROFRONTEND_NAME@1.2.3'`).
- **hubFunction** (function) - Required - A function that receives a `hub` object and must call `hub.renderAt(element, data?)` to specify where to render the micro frontend.
- **element** (HTMLElement) - Required - A valid DOM element where the micro frontend will be rendered.
- **data** (object) - Optional - Additional information passed to the micro frontend context. This object does not accept functions.
- **options** (object) - Optional - An object with the following properties:
- **errorCallback** (function) - Optional - A function to handle any errors that occur during the micro frontend require process.
- **priority** (string) - Optional - Determines the priority with which FrontHub requests the micro frontend assets. Possible values: `'high'` (default) or `'medium'`. When `'medium'`, the micro frontend is loaded after `document.readyState` is `complete`.
### Request Example
```javascript
fronthub('requireMicrofrontend', 'YOUR_MICROFRONTEND_NAME', function (hub) {
hub.renderAt(document.getElementById('target-id-element'))
})
```
### Request Example with Fixed Version
```javascript
fronthub(
'requireMicrofrontend',
'YOUR_MICROFRONTEND_NAME@THE_SEMVER_VERSION',
function (hub) {
hub.renderAt(document.getElementById('target-id-element'))
}
)
```
### Request Example with Data
```javascript
fronthub('requireMicrofrontend', 'YOUR_MICROFRONTEND_NAME', function (hub) {
hub.renderAt(document.getElementById('target-id-element'),
{
prop: true,
customData: {
foo: 'bar'
}
}
)
})
```
### Request Example with Options
```javascript
fronthub('requireMicrofrontend', 'YOUR_MICROFRONTEND_NAME', function (hub) {
hub.renderAt(document.getElementById('target-id-element'))
}, {
errorCallback: error => {
MyCustomErrorService.error(error)
console.error(`Failed to load MFE: ${err}`)
},
priority: 'medium' // or 'high'
})
```
### Response
This command does not return a value. The micro frontend is rendered asynchronously at the specified element. Errors can be handled via the `errorCallback` option.
```
--------------------------------
### Request multiple micro frontends
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Configure multiple dependencies in front-hub.config.js and request them using fixed or latest versions.
```javascript
mfeDependencies: ['navbar@1.0.1', 'navbar@1.0.2', 'sidebar@latest']
```
```javascript
/// With fixed version
/// As latest
```
--------------------------------
### Configure Application Host repository property
Source: https://front-hub.rdstation.com.br/docs/fake-repository
In the Application Host, set the repository property to the address indicated by the Fake repository command output.
```html
```
--------------------------------
### Implementing a Basic Track Listener
Source: https://front-hub.rdstation.com.br/docs/instrumentation
Use the track property to listen to events on the Application Host.
```javascript
fronthub('instrumentation', {
track: function (context, next) {
console.log(context)
next()
},
})
```
--------------------------------
### Register MFE version in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/microfrontend-component
Add the micro frontend name and version to the 'mfeDependencies' array in the front-hub.config.js file. Using '@latest' fetches the latest active version from Fronthub.
```javascript
...rest_of_configs,
mfeDependencies: ['MFE_NAME@latest']
```
--------------------------------
### Configure multiple APIs in front-hub.config.js
Source: https://front-hub.rdstation.com.br/docs/fake-api
Define services for each API your microfrontend connects to, specifying name, rootDir, and endpoints for production and staging.
```javascript
module.exports = {
// ...
services: [
{
name: 'analytics-api',
rootDir: '/fake-analytics-api',
endpoints: {
production: 'https://api.analytics.com',
staging: 'https://api-staging.analytics.com',
},
},
{
name: 'leads-api',
rootDir: '/fake-leads-api',
endpoints: {
production: 'https://leads.com/api',
staging: 'https://leads-staging.com/api',
},
},
],
// ...
}
```
--------------------------------
### Configure Auto in package.json
Source: https://front-hub.rdstation.com.br/docs/lib-releases
Full configuration for the Auto tool, including plugins and custom release labels for versioning.
```json
"auto": {
"plugins": [
[
"npm",
{
"setRcToken": false
}
],
"first-time-contributor",
"released"
],
"onlyPublishWithReleaseLabel": true,
"labels": [
{
"name": "version:major",
"changelogTitle": "💥 Breaking Change",
"description": "Increment the major version",
"releaseType": "major",
"color": "#C5000B",
"overwrite": true
},
{
"name": "version:minor",
"changelogTitle": "🚀 Enhancement",
"description": "Increment the minor version",
"releaseType": "minor",
"color": "#F1A60E",
"overwrite": true
},
{
"name": "version:patch",
"changelogTitle": "🐛 Bug Fix",
"description": "Increment the patch version",
"releaseType": "patch",
"color": "#870048",
"overwrite": true
},
{
"name": "version:performance",
"changelogTitle": "🏎 Performance",
"description": "Improve performance of an existing feature",
"releaseType": "patch",
"color": "#f4b2d8",
"overwrite": true
},
{
"name": "version:internal",
"changelogTitle": "🏠 Internal",
"description": "Changes only affect the internal API and it doesn't generate a new version",
"releaseType": "none",
"color": "#696969",
"overwrite": true
},
{
"name": "version:docs",
"changelogTitle": "📝 Documentation",
"description": "Changes only affect the documentation",
"releaseType": "none",
"color": "#cfd3d7",
"overwrite": true
},
{
"name": "version:dependencies",
"changelogTitle": "🔩 Dependency Updates",
"description": "Update one or more dependencies version",
"releaseType": "none",
"color": "#8732bc",
"overwrite": true
},
{
"name": "version:release",
"description": "Create a release when this pr is merged",
"releaseType": "release",
"color": "#007f70",
"overwrite": true
}
]
}
```
--------------------------------
### Configure Development Host
Source: https://front-hub.rdstation.com.br/docs/config
Sets the application host file path for development. This includes the configuration in front-hub.config.js and the implementation in applicationHost.js.
```javascript
module.exports = {
dev: {
host: './applicationHost.js',
},
}
```
```javascript
module.exports = fronthub => {
return fronthub.requireMicrofrontend(MICROFRONTEND_NAME, hub =>
hub.renderAt('#target-id-element'),
)
}
```