Billy Chandler

Billy Chandler

1566457800

Creating Micro Frontends using Web Components (with Angular and React)

If you’re React or Angular, Ember or Vue let’s create a place where they all can live together in perfect harmony using web components.

Using web components as a wrapper for both Angular and React components, I am going to show them working alongside each other in a single application. I will also pass data to both components from the parent container, and back again. 

Our finished product will look like this:

https://github.com/chriskitson/micro-frontends-with-web-components

PrerequisitesTo enable us to focus on the important pieces, I have coded everything and uploaded it to my github

This isn’t a deep-dive by any means, but I will walk-through the important pieces for web component support in Angular and React.* If you would like to complete some of the other frameworks (Vue, Ember etc), feel free to create a pull request on my repo!

I’ve used the Angular CLI to generate a starting point for our Angular project. You should at least be familiar with this tool so you can navigate the code

As our end goal here is web components, we will be composing static JavaScript files as micro-services. To do this I will use serve on my local environment, which is an excellent tool for serving static files using node

Angular component as custom element

As Angular seem to be adopting web components (with Angular elements), you can serve Angular components as web components with a few small tweaks to the default Angular CLI generated project.

Everything should be working correctly in the /micro-fe-ng directory, all you need to do is install the dependencies and run the start script:

cd micro-fe-ng/
npm i
npm start

Now our Angular micro-frontend defining our custom element as <ng-el />should be running at http://localhost:5001/main.js.

Note: we are serving our files through localhost on different ports, but they could easily be sitting inside multiple micro-services sharing the same DNS.

If you’re interested in how this was achieved here is a rundown on the required changes:

We need a couple of new dependencies:

Angular’s support for custom elements (@angular/elements) and ngx-build-plus which is an alternative build tool for Angular (this has decent support for Angular elements):

npm i @angular/elements ngx-build-plus -D

We also need some changes to our package.json to build our Angular project and serve our project as custom elements:

micro-fe-ng/package.json:

"start": "npm run build && serve -l 5001 dist/micro-fe-ng",
"build": "ng build --prod --output-hashing none --single-bundle true",

We need to define the custom element(s) in our app.module.ts as below:

micro-fe-ng/src/app/app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { AppComponent } from './app.component';
import { CustomelementComponent } from './customelement/customelement.component';
@NgModule({
  declarations: [
    AppComponent,
    CustomelementComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [],
  entryComponents: [
    AppComponent,
    CustomelementComponent
  ]
})
export class AppModule {
  constructor(private injector: Injector) {}
  ngDoBootstrap(): void {
    const { injector } = this;
    // create custom elements from angular components
    const ngCustomElement = createCustomElement(CustomelementComponent, { injector });
    // define in browser registry
    customElements.define('ng-el', ngCustomElement);
  }
}

Finally, we need to tell Angular to use the ngx-build-plus build tool by specifying it in three places inside angular.json as shown below:

Ngx-build-plus returns the built project as a single JS file which is a requirement for web components to work as a single service.

micro-fe-ng/angular.json:

...
"architect": {
  "build": {
    "builder": "ngx-build-plus:build",
    ....
  "serve": {
    "builder": "ngx-build-plus:dev-server",
    ...
  "test": {
    "builder": "ngx-build-plus:karma",

React component as custom element

As React doesn’t have out-of-the-box support for web components, we will have to write a little more code than before to wrap a standard React component and present it as a native web component (custom element).

Much like React components, custom elements (web components) also have lifecycle hooks which you can access via callback methods.

By using the custom element API’s connectedCallback() and disconnectedCallback() lifecycle methods, we can map these to render()and unmount() of our React component respectively, as shown below:

class MyCustomElement extends HTMLElement {
  constructor() {
    super();
  }
  connectedCallback() {
    ReactDOM.render(<MyReactComponent />, this);
  }
  disconnectedCallback(){
    ReactDOM.unmountComponentAtNode(this);
  }
}

I’ve taken this a stage deeper by also mapping React props and events. If you want to check that out, then take a look at/micro-fe-react/src/index.js.

Everything should be working nicely in the example repository so you can do the following to get the React micro-service up and running:

cd micro-fe-react/
npm i
npm start

Now our React micro-frontend defining our custom element as <react-el /> should be running at http://localhost:5002/main.js

Micro-frontend wrapper

We have two micro-frontend services; one for an Angular component and one for a React component.

Now let’s create a world where they can live alongside each other…

Everything should be working correctly in the /micro-fe-wrapper directory, all you need to do is install the dependencies and run the start script:

cd micro-fe-wrapper/
npm i
npm start

Now our micro-frontend wrapper should be running at http://localhost:5000.

For an explanation of how it works, read on….

As web components are part of the native HTML spec we don’t need to do anything too fancy to bring them together.

In the real-world you might want to use a framework for better code structure and data binding etc., but in the interest of simplicity, let’s just stick with vanilla HTML/JS.

micro-fe-wrapper/index.html:

We need to include some external dependencies from a CDN:

  • zone.js is required by Angular. It’s good practice to include this once in the wrapper application as you cannot have multiple versions on the same page.
  • custom-elements-es5-adapter.js gives us Custom Element support inside our browser.

In addition we should include the JS files from our component services which we built and deployed in the previous steps:

<script src="https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.9.1/zone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.2.10/custom-elements-es5-adapter.js"></script>
<script src="http://localhost:5001/main.js"></script>
<script src="http://localhost:5002/main.js"></script>

I have defined a method as tellComponents(), which should inject custom element tags: <ng-el /> for Angular and <react-el /> for React into our page.

I am also passing an attribute name using setAttribute() to simulate the wrapper application talking to the components.

I am also listening for an event called helloEvt using addEventListener()which will listen for events coming from our components, enabling them to talk to our parent application and potentially other components. Pretty cool!

There’s a slight difference in attribute names for the helloEvt() between React and Angular. This is due to differing conventions between the frameworks. I’ll explain more later…

function tellComponents() {
  const name = document.getElementById('yourName').value;
const reactEl = document.createElement('react-el');
  reactEl.setAttribute('name', name);
  reactEl.setAttribute('onHelloEvt', 'onHelloEvt');
  reactEl.addEventListener('onHelloEvt', (e) => helloEvent('react'));
  const reactElContainer =  document.getElementById('react-container')
  if (reactElContainer.children.length > 0) {
    reactElContainer.removeChild(reactElContainer.children[0]);
  }
  reactElContainer.appendChild(reactEl);
const ngEl = document.createElement('ng-el');
  ngEl.setAttribute('name', name);
  ngEl.addEventListener('helloEvt', (e) => helloEvent('angular'));
  const ngElContainer =  document.getElementById('ng-container');
  if (ngElContainer.children.length > 0) {
    ngElContainer.removeChild(ngElContainer.children[0]);
  }
  ngElContainer.appendChild(ngEl);
}

Passing values to and from components

Remember the name attribute we passed to our custom elements? It’s actually quite straightforward to read this value in our components.

In Angular we simply reference an Input:

export class CustomelementComponent implements OnInit {
  @Input() name: string;
  ...
}

This makes the value available in our template:

<p>Hello <strong>{{name}}</strong> from your friendly Angular component.</p>

In React it will be passed to the component as a prop:

export class ExampleComponent extends React.Component {

static propTypes = {
name: PropTypes.string
}
static defaultProps = {
name: “Chris”
}
render() {
const { name } = this.props;
return (
<div className=“exampleComponent”>
<p>Hello <strong>{name}</strong> from your friendly React component.</p>
</div>
)
}
}

Sending events from our components is almost as simple as we are listening for helloEvt.

In Angular, all we need to do is specify an Output:

export class CustomelementComponent implements OnInit {
@Input() name: string;
@Output() helloEvt: EventEmitter<string> = new EventEmitter();

}

Then we can call this event from our template:

<button type=“submit” (click)=“helloEvt.next()”>Say hello</button>

Note that EventEmitter creates an observable in Angular, hence we need to invoke next().

In React, our component wrapper (micro-fe-react/src/index.js) will look for props prefixed with “on” and treat them as events e.g. onClick()onFocus() etc for native events. This is why we called our custom event onHelloEvt() for React.

Events are treated as props in React, so all we need to do is define the prop and call it as a onClick() handler. That’s it!

export class ExampleComponent extends React.Component {
static propTypes = {
name: PropTypes.string,
onHelloEvt: PropTypes.func
}
static defaultProps = {
name: “Chris”
}
render() {
const { name, onHelloEvt } = this.props;

return (
  &lt;div className="exampleComponent"&gt;
    &lt;button type="submit" onClick={onHelloEvt}&gt;Say hello&lt;/button&gt;
  &lt;/div&gt;
)

}
}

Conclusion

Using these concepts you should be able to create some really powerful applications mixing both Angular and React components by using the Web Component Custom Element spec. Many of the huge web platforms out there already invoke similar techniques to compose micro-frontends.

There are many pros and cons for why mixing frameworks might be beneficial or problematic (depending on your use case); considering things like adaptability, scalability, performance, security, resourcing, browser support etc.

Here’s a reminder of my github if you haven’t already checked it out. Enjoy!!

Originally published by Chris Kitson at https://medium.com

Useful article:

The Strengths and Benefits of Micro Frontends

#angular #reactjs #web-development #microservices #javascript

What is GEEK

Buddha Community

Creating Micro Frontends using Web Components (with Angular and React)
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Roberta  Ward

Roberta Ward

1593490740

Micro-Frontend using Web Components

First of all, what is Micro Frontend?

Micro Frontend is a micro service approach to front end web development. The concept of Micro Frontend is to think about a web application as a composition of features owned by different independent teams. Each team has a distinct area of business or mission it cares about and specialises in. A team is cross functional and develops its features end-to-end.

Micro front end architecture

We’ve established a good micro service architecture for our backends. It’s time to apply the same principles to our front ends. A lot of firms are moving towards micro frontend from classic monolith architecture like Google, Amazon, Salesforce, Zalando, ThoughtWorks etc.

Amazon’s architecture for micro frontend

There are various implementations for micro frontend approach. But, in this article, we’d be talking about micro frontend implementation using Web Components only.

What are Web Components?

In modern web development, everyone is using components to encapsulate UI functionalities. Web components are low-level browser API that helps us to extend the browser with new components, they provide us a standard interface for defining new components. Web components have a standard way of creating components that use HTML and DOM API that every other front end framework uses and a common way of receiving and sending data using props and events.

Web component simply tells the browser WHEN and WHERE to create a component, not HOW to create a component.

Web Components comprises of 3 concepts:

  1. Custom Elements: Set of JavaScript APIs that allow you to create your own HTML elements and define the way they behave.
  2. Shadow DOM: A private DOM that is scoped to your component only and capable of isolating CSS and JavaScript.
  3. HTML templates. New HTML tags that allows us to create templates for your components.

In simpler terms, you can create your own HTML selector, like

#angular #github #micro-frontends #web-components #react

Top Enterprise Angular Web Apps Development Company in USA

AppClues Infotech is one of the leading Enterprise Angular Web Apps Development Company in USA. Our dedicated & highly experienced Angular app developers build top-grade Angular apps for your business with immersive technology & superior functionalities.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top enterprise angular web apps development company in usa #enterprise angular web apps development #hire enterprise angular web apps developers #best enterprise angular web app services #custom enterprise angular web apps solution #professional enterprise angular web apps developers

Roberta  Ward

Roberta Ward

1595344320

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill.

Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.

Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!

And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!

If you are still not aware of it, don’t worry as Georgia Byng has well said,

“No time is better than the present”

– Georgia Byng, a British children’s writer, illustrator, actress and film producer.

No matter if you are a developer (be it front-end or back-end) or a data scientisttester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.

From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.

How to upgrade your skills?

Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.

These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.

Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).

xlr8rs make your development real fast by just adding your core business logic to the template.

If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂

Confused with which technology to start with?

To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.

Since we believe:

“There’s always a scope of improvement“

If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.

#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade

Why the industries are choosing to react instead of angular - INFO AT ONE

Angular JS is a typescript-based application developed by Google. It’s an open-source web application framework, specifically made for the front end Web developers. As we know that the Angular is created by Google it gets very good support from Google and some individual communities of developers.

Read More:- https://infoatone.com/why-the-industries-are-choosing-to-react-instead-of-angular/

#angular #angular and react #js cons of angular #cons of react js #difference between angular and react js #pros of react js