6.1.21 • Published 2 years ago

@ynnck/ng-universal v6.1.21

Weekly downloads
52
License
MIT
Repository
-
Last release
2 years ago

Description

Angular Universal module for Nest.

Installation

Using the Angular CLI:

$ ng add @nestjs/ng-universal

Or manually:

$ npm i @nestjs/ng-universal

Example

See full example here.

Usage

If you have installed the module manually, you need to import AngularUniversalModule in your Nest application.

import { Module } from '@nestjs/common';
import { join } from 'path';
import { AngularUniversalModule } from '@nestjs/ng-universal';

@Module({
  imports: [
    AngularUniversalModule.forRoot({
      bootstrap: AppServerModule,
      viewsPath: join(process.cwd(), 'dist/{APP_NAME}/browser')
    })
  ]
})
export class ApplicationModule {}

API Spec

The forRoot() method takes an options object with a few useful properties.

PropertyTypeDescription
viewsPathstringThe directory where the module should look for client bundle (Angular app)
bootstrapFunctionAngular server module reference (AppServerModule).
templatePathstring?Path to index file (default: {viewsPaths}/index.html)
rootStaticPathstring?Static files root directory (default: *.*)
renderPathstring?Path to render Angular app (default: *)
extraProvidersStaticProvider[]?The platform level providers for the current render request
inlineCriticalCssboolean?Reduce render blocking requests by inlining critical CSS. (default: true)
cacheboolean? | object?Cache options, description below (default: true)
errorHandlerFunction?Callback to be called in case of a rendering error

Cache

PropertyTypeDescription
expiresInnumber?Cache expiration in milliseconds (default: 60000)
storageCacheStorage?Interface for implementing custom cache storage (default: in memory)
keyGeneratorCacheKeyGenerator?Interface for implementing custom cache key generation logic (default: by url)
AngularUniversalModule.forRoot({
  bootstrap: AppServerModule,
  viewsPath: join(process.cwd(), 'dist/{APP_NAME}/browser'),
  cache: {
    storage: {
      useValue: new InMemoryCacheStorage(),
      // or
      // useClass: RedisCacheStorage,
    },
    expiresIn: DEFAULT_CACHE_EXPIRATION_TIME,
    keyGenerator: new CustomCacheKeyGenerator()
  }
});

Example for CacheKeyGenerator:

export class CustomCacheKeyGenerator implements CacheKeyGenerator {
  generateCacheKey(request: Request): string {
    const md = new MobileDetect(request.headers['user-agent']);
    const isMobile = md.mobile() ? 'mobile' : 'desktop';
    return (request.hostname + request.originalUrl + isMobile).toLowerCase();
  }
}

Request and Response Providers

This tool uses @nguniversal/express-engine and will properly provide access to the Express Request and Response objects in you Angular components. Note that tokens must be imported from the @nestjs/ng-universal/tokens, not @nguniversal/express-engine/tokens.

This is useful for things like setting the response code to 404 when your Angular router can't find a page (i.e. path: '**' in routing):

import { Response } from 'express';
import { Component, Inject, Optional, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { RESPONSE } from '@nestjs/ng-universal/tokens';

@Component({
  selector: 'my-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.scss']
})
export class NotFoundComponent {
  constructor(
    @Inject(PLATFORM_ID)
    private readonly platformId: any,
    @Optional()
    @Inject(RESPONSE)
    res: Response
  ) {
    // `res` is the express response, only available on the server
    if (isPlatformServer(this.platformId)) {
      res.status(404);
    }
  }
}

Custom Webpack

In some situations, it may be required to customize the webpack build while using @nestjs/ng-universal, especially when additional dependencies are included (that rely on native Node.js code).

To add a customizable webpack config to your project, it is recommended to install @angular-builders/custom-webpack in the project and to set your builders appropriately.

Example Custom Webpack

// webpack.config.ts
import { Configuration, IgnorePlugin } from 'webpack'
import {
  CustomWebpackBrowserSchema,
  TargetOptions
} from '@angular-builders/custom-webpack'
import nodeExternals from 'webpack-node-externals'

export default (
  config: Configuration
  _options: CustomWebpackBrowserSchema,
  targetOptions: TargetOptions
) => {
  if (targetOptions.target === 'server') {
    config.resolve?.extensions?.push('.mjs', '.graphql', '.gql')

    config.module?.rules?.push({
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto'
    });

    config.externalsPresets = { node: true }

    (config.externals as Array<any>).push(
      nodeExternals({ allowlist: [/^(?!(livereload|concurrently|fsevents)).*/]})
    );

    config.plugins?.push(
      new IgnorePlugin({
        checkResource: (resource: string) => {
          const lazyImports = [
            '@nestjs/microservices',
            '@nestjs/microservices/microservices-module',
            '@nestjs/websockets/socket-module',
            'cache-manager',
            'class-validator',
            'class-transform',
          ];

          if (!lazyImpots.includes(resource)) {
            return false;
          }

          try {
            require.resolve(resource)
          } catch (_err: any) {
            return true;
          }
          return false;
        }
      })
    );
  }
  return config;
};

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

6.1.17

2 years ago

6.1.16

2 years ago

6.1.15

2 years ago

6.1.14

2 years ago

6.1.19

2 years ago

6.1.18

2 years ago

5.0.12

2 years ago

5.0.13

2 years ago

6.1.0

2 years ago

6.1.13

2 years ago

6.1.2

2 years ago

6.1.12

2 years ago

6.1.1

2 years ago

6.1.11

2 years ago

6.1.4

2 years ago

6.1.10

2 years ago

6.1.3

2 years ago

6.1.20

2 years ago

6.1.21

2 years ago

6.1.6

2 years ago

6.1.5

2 years ago

6.1.8

2 years ago

6.1.7

2 years ago

6.1.9

2 years ago

5.0.6

2 years ago

5.0.5

2 years ago

5.0.4

2 years ago

5.0.3

3 years ago

6.0.1

2 years ago

6.0.0

2 years ago

6.0.2

2 years ago

6.0.5

2 years ago

6.0.4

2 years ago

6.0.7

2 years ago

6.0.6

2 years ago

5.0.7

2 years ago

4.3.3

3 years ago

4.3.2

3 years ago

4.3.1

3 years ago

4.3.0

3 years ago

4.2.0

3 years ago