How Can You Integrate Angular, Angular Universal, And NestJS In One Project Within An Nx Monorepo?

Asked 2 weeks ago
Answer 1
Viewed 33
1

Before SPAs Server-side delivering was something typical with php, java and such. Html css and js was utilized to be made from the backend and the program gets the last duplicate for delivering and some client communication. Presently individuals are attempting to get once again to that arrangement however utilizing apparatuses that are worked for SPA isn't effective in that climate.

Presently assuming we attempt to investigate NestJS we would see that it has a part called MVC which is really like the manner in which JavaEE works. While it is as yet thought about SSR. It's not the SSR you would see with a cutting edge structure. There is plausible that we could return to the old arcade SSR'ing like with thymeleaf and Java where Rakish turns into the Layout Motor and NestJS assumes Java's part.

This blog investigates the reconciliation of Precise + Rakish General, and NestJS inside a Nx Monorepo, attempting to achieve this methodology.

Here is a concise prologue to every system or device we are involving in this blog.

Angular

Rakish is a famous open-source web application system created and kept up with by Google. It is intended for building dynamic single-page applications (SPAs) with a solid accentuation on execution and viability. Precise gives a complete arrangement of instruments and elements.

Angular Universal

Rakish All inclusive is an innovation that stretches out Precise's capacities to empower server-side delivering (SSR) of Rakish applications. SSR works on the exhibition and Search engine optimization of web applications by delivering the underlying HTML on the server instead of the client. Key advantages of Precise Widespread include:

Further developed Execution: Quicker introductory page loads and better apparent execution.
Improved Website optimization: Completely delivered HTML content is more available to web index crawlers.
Better Client Experience: Decreases the chance to intuitive, giving a smoother client experience.

NestJS

NestJS is a moderate, extensible Node.js structure for building productive and versatile server-side applications. Motivated by Rakish, NestJS use TypeScript and embraces a measured engineering, making it a characteristic fit for full-stack improvement. Key highlights of NestJS include:

Measured Design: Empowers a secluded construction for better association and versatility.
Reliance Infusion: Improves on the administration of conditions and upgrades testability.
Strong CLI: Gives a powerful order line interface for producing and overseeing code.
Wide Similarity: Works flawlessly with different libraries and systems, including GraphQL, WebSockets, from there, the sky is the limit.

Nx Monorepo

Nx is a high level arrangement of extensible dev apparatuses for monorepos, which assists you with dealing with your work area proficiently. A monorepo is a rendition controlled code storehouse that holds many ventures, frequently including different applications and libraries. Nx gives a few advantages to overseeing such a work area:

  • Incorporated Improvement Experience: Works with the advancement of numerous ventures with a common codebase.
  • Code Sharing and Reusability: Advances the reuse of code and decreases duplication across projects.
  • Progressed Tooling: Offers integral assets for code age, testing, and building, improving designer efficiency.
  • Reliable Code Quality: Guarantees predictable code quality and principles across the whole monorepo.
  • In the accompanying segments, we will dive into the arrangement cycle for consolidating these advances into a strong undertaking.

Note: This is a paper and it very well may be improved for a superior use. In the event that you likewise have an alternate methodology or thinking, feel free to it in the conversation segment.

0. Create an Nx Workspace

In the event that you're not previously involving Nx for overseeing you projects in a similar vault, I encourage you to think about it. By and by, considering that this blog is for the end goal of learning, we'll make reference to it at any rate.

To begin with Nx you can adhere to the guidelines gave in its true documentation and make the monorepo with any tech stack you like.

Note: you ought to have nodejs and npm introduced on your machine.

npx create-nx-workspace@latest

You start the formation of a Nx work area utilizing this order then you ought to follow with the cycle to make it helpful.

1. Create Angular Microfrontend inside Nx

Suppose we maintain that our application should be called site home.

All things considered, utilizing the accompanying order and in the wake of picking the favored styling type (e.g css, scss… ) alongside the testing climate (e.g cypress) and the bundler (e.g webpack), you ought to have effectively made a non-independent rakish application with Nx.

npx nx g @nx/angular:application website-nest-mfe --directory website-nest/mfe --standalone false
 

Note: The ongoing paper expects you might want to utilize a non-independent application part (for example with NgModule).

2. Integrate Angular Universal

npx nx g @nx/angular:setup-ssr --project=website-nest-mfe
 

Here we are adding Precise Widespread to our Rakish Microfront to utilize its ssr abilities.

Note: you can find the microfrontend's undertaking name inside its relative project.json

3. Add NestJS to Angular (Same Host)

Presently adding NestJS to cause it to participate with rakish may be precarious on the grounds that we need to set this up physically.

To start with, inside mfe catalog make another registry and name it server.
Then, make a main.ts record inside mfe/server with the accompanying code.

/**
 * This is not a production server yet!
 * This is only a minimal backend to get started.
 */


import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';


async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const globalPrefix = '';
  app.setGlobalPrefix(globalPrefix);
  const port = process.env['PORT'] || 3000;
  await app.listen(port);
  Logger.log(
    `???? Application is running on: http://localhost:${port}/${globalPrefix}`
  );
}


// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = (mainModule && mainModule.filename) || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  bootstrap().catch((err) => console.error(err));
}

This record will be answerable for building NestJS Application and Delivering Precise's index.html utilizing express.
However, an other record ought to be added to the server registry is expected to get that going. It is app.module.ts.

A fundamental app.module.ts nestjs document inside mfe/server ought to be this way:

import { Module } from '@nestjs/common';
import { AngularUniversalModule } from '@nestjs/ng-universal';
import { join } from 'path';
import { AppServerModule } from '../src/main.server';
// import { AppController } from './app.controller';


@Module({
  imports: [
    AngularUniversalModule.forRoot({
      bootstrap: AppServerModule,
      viewsPath: join(process.cwd(), ''),
    }),
  ],
  // controllers: [AppController],
})
export class AppModule {}

The mfe ought to have the option to decipher nestjs code while coding with it so we ought to refresh tsconfig:=

mfe/tsconfig.app.jso

{
  ….
  "include": ["src/**/*.d.ts", "server/**/*.ts"],
  "exclude": [
    "jest.config.ts",
    "src/**/*.test.ts",
    "src/**/*.spec.ts",
    "server/**/*.spec.ts"
  ]
}

Presently update likewise mfe/server.ts of precise general to arrange it to order nestjs:

import 'zone.js/node';

import './server/main';

export * from './src/main.server';

Following up, we ought to likewise refresh mfe/src/main.server.ts and mfe/src/main.ts
#mfe/src/main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch((err) => console.error(err));
});

#mfe/src/main.server.ts

Answered 2 weeks ago Gianna EleanorGianna Eleanor