- Notifications
You must be signed in to change notification settings - Fork68
Angular Universal module for Nest framework (node.js) 🌷
License
nestjs/ng-universal
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A progressiveNode.js framework for building efficient and scalable server-side applications.
AngularUniversal module forNest.
Using the Angular CLI:
$ ng add @nestjs/ng-universal
Or manually:
$ npm i @nestjs/ng-universal
See full examplehere.
If you have installed the module manually, you need to importAngularUniversalModule 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')})]})exportclassApplicationModule{}
TheforRoot() method takes an options object with a few useful properties.
| Property | Type | Description |
|---|---|---|
viewsPath | string | The directory where the module should look for client bundle (Angular app) |
bootstrap | Function | Angular server module reference (AppServerModule). |
templatePath | string? | Path to index file (default:{viewsPaths}/index.html) |
rootStaticPath | string? | Static files root directory (default:*.*) |
renderPath | string? | Path to render Angular app (default:*) |
extraProviders | StaticProvider[]? | The platform level providers for the current render request |
inlineCriticalCss | boolean? | Reduce render blocking requests by inlining critical CSS. (default: true) |
cache | boolean? | object? | Cache options, description below (default:true) |
errorHandler | Function? | Callback to be called in case of a rendering error |
| Property | Type | Description |
|---|---|---|
expiresIn | number? | Cache expiration in milliseconds (default:60000) |
storage | CacheStorage? | Interface for implementing custom cache storage (default: in memory) |
keyGenerator | CacheKeyGenerator? | 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:newInMemoryCacheStorage(),expiresIn:DEFAULT_CACHE_EXPIRATION_TIME,keyGenerator:newCustomCacheKeyGenerator()}});
exportclassCustomCacheKeyGeneratorimplementsCacheKeyGenerator{generateCacheKey(request:Request):string{constmd=newMobileDetect(request.headers['user-agent']);constisMobile=md.mobile() ?'mobile' :'desktop';return(request.hostname+request.originalUrl+isMobile).toLowerCase();}}
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']})exportclassNotFoundComponent{constructor( @Inject(PLATFORM_ID)privatereadonlyplatformId:any, @Optional() @Inject(RESPONSE)res:Response){// `res` is the express response, only available on the serverif(isPlatformServer(this.platformId)){res.status(404);}}}
In some situations, it may be required to customize thewebpack build while using@nestjs/ng-universal, especially when additional dependencies are included (that rely on native Node.js code).
To add a customizablewebpack config to your project, it is recommended to install@angular-builders/custom-webpack in the project and to set your builders appropriately.
// webpack.config.tsimport{Configuration,IgnorePlugin}from'webpack'import{CustomWebpackBrowserSchema,TargetOptions}from'@angular-builders/custom-webpack'importnodeExternalsfrom'webpack-node-externals'exportdefault(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.externalsasArray<any>).push(nodeExternals({allowlist:[/^(?!(livereload|concurrently|fsevents)).*/]}));config.plugins?.push(newIgnorePlugin({checkResource:(resource:string)=>{constlazyImports=['@nestjs/microservices','@nestjs/microservices/microservices-module','@nestjs/websockets/socket-module','cache-manager','class-validator','class-transform',];if(!lazyImpots.includes(resource)){returnfalse;}try{require.resolve(resource)}catch(_err:any){returntrue;}returnfalse;}}));}returnconfig;};
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, pleaseread more here.
- Author -Kamil Myśliwiec
- Website -https://nestjs.com
- Twitter -@nestframework
Nest isMIT licensed.
About
Angular Universal module for Nest framework (node.js) 🌷
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.