Skip to content

Commit

Permalink
feat(@nguniversal/common): add experimental SSR project Clover
Browse files Browse the repository at this point in the history
# @nguniversal/common/clover

- What if Angular SSR didn't require the complex `@nguniversal` and `@angular/platform-server` packages on boarding?
- What if we `Window is undefined` error was a thing of the past?
- What if you don't need multiple builds for an SSR/prerender application?
- What if an application shell can be generated without an extra build?

## Supported features

- [x] Inline critical CSS
- [x] State transfer
- [x] Re-use component styles generated on the server
- [x] i18n
- [x] Hybrid rendering
- [x] Server side rendering

# Planned features
- [ ] App-shell
- [ ] Pre-rendering
- [ ] Schematics

## Try it out

### Install the dependencies
```
npm install @nguniversal/common express --save
```

### Include the module in the application

#### app/app.module.ts

```diff
  import { NgModule } from '@angular/core';
  import { BrowserModule } from '@angular/platform-browser';

  import { AppRoutingModule } from './app-routing.module';
  import { AppComponent } from './app.component';
  import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
+ import { RendererModule, TransferHttpCacheModule } from '@nguniversal/common/clover';

  @NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
-     BrowserModule,
+     BrowserModule.withServerTransition({
+      appId: 'myapp',
+     }),
+     RendererModule.forRoot(),
+     TransferHttpCacheModule,
      AppRoutingModule,
      BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

#### server.js
```ts
const express = require('express');
const { Engine } = require('@nguniversal/common/clover/server');
const { join } = require('path');
const { format } = require('url');

const PORT = 8080;
const DIST = join(__dirname, 'dist');

const app = express();
app.set('views', DIST);

app.get('*.*', express.static(DIST, {
  maxAge: '1y',
  fallthrough: false,
}));

// Redirect to default locale
// app.get(/^(\/|\/favicon\.ico)$/, (req, res) => {
//   res.redirect(301, `/en-US${req.originalUrl}`);
// });

const ssr = new Engine();
app.get('*', (req, res, next) => {
  ssr.render({
    publicPath: DIST,
    url: format({
      protocol: req.protocol,
      host: `localhost:${PORT}`,
      pathname: req.path,
      query: req.query,
    }),
    headers: req.headers,
  })
    .then(html => res.send(html))
    .catch(err => next(err));
});

app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});
```

### Running the application
```
ng build
node server.js
```
  • Loading branch information
alan-agius4 committed Apr 28, 2021
1 parent ad36397 commit c4b7be3
Show file tree
Hide file tree
Showing 45 changed files with 1,257 additions and 15 deletions.
27 changes: 27 additions & 0 deletions integration/clover/README.md
@@ -0,0 +1,27 @@
# universal-integration

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.0-next.4.

## Development server

Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

## Code scaffolding

Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.

## Build

Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.

## Running unit tests

Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).

## Running end-to-end tests

Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).

## Further help

To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
65 changes: 65 additions & 0 deletions integration/clover/angular.json
@@ -0,0 +1,65 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"clover": {
"projectType": "application",
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"progress": false,
"outputPath": "dist/clover/browser",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
}
}
}
},
"defaultProject": "clover"
}
4 changes: 4 additions & 0 deletions integration/clover/browserslist
@@ -0,0 +1,4 @@
# We want to run tests large with ever green browser so that
# we never trigger differential loading as this will slow down the tests.

last 2 Chrome versions
36 changes: 36 additions & 0 deletions integration/clover/package.json
@@ -0,0 +1,36 @@
{
"name": "universal-integration",
"version": "0.0.0",
"description": "Integration tests for @nguniversal",
"repository": {
"type": "git",
"url": "https://github.com/angular/universal.git"
},
"scripts": {
"ng": "ng",
"test": "yarn build && node test.js",
"build": "ng build --configuration production"
},
"private": true,
"dependencies": {
"@angular/animations": "file:../../node_modules/@angular/animations",
"@angular/common": "file:../../node_modules/@angular/common",
"@angular/compiler": "file:../../node_modules/@angular/compiler",
"@angular/compiler-cli": "file:../../node_modules/@angular/compiler-cli",
"@angular/core": "file:../../node_modules/@angular/core",
"@angular/platform-browser": "file:../../node_modules/@angular/platform-browser",
"@angular/platform-browser-dynamic": "file:../../node_modules/@angular/platform-browser-dynamic",
"@angular/platform-server": "file:../../node_modules/@angular/platform-server",
"@angular/router": "file:../../node_modules/@angular/router",
"@nguniversal/common": "file:../../dist/modules-dist/common",
"rxjs": "file:../../node_modules/rxjs",
"zone.js": "file:../../node_modules/zone.js"
},
"devDependencies": {
"@angular-devkit/build-angular": "file:../../node_modules/@angular-devkit/build-angular",
"@angular/cli": "file:../../node_modules/@angular/cli",
"@angular/compiler-cli": "file:../../node_modules/@angular/compiler-cli",
"@types/node": "file:../../node_modules/@types/node",
"typescript": "file:../../node_modules/typescript"
}
}
11 changes: 11 additions & 0 deletions integration/clover/src/app/app-routing.module.ts
@@ -0,0 +1,11 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
23 changes: 23 additions & 0 deletions integration/clover/src/app/app.component.ts
@@ -0,0 +1,23 @@
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
selector: 'app-root',
template: `
<div>Hello {{ title }}!</div>
<span class="href-check">{{href}}</span>
`,
styles: [`
div {
font-weight: bold;
}
`]
})
export class AppComponent {
title = 'world';
href: string;

constructor(@Inject(DOCUMENT) doc: Document) {
this.href = doc.location.href;
}
}
21 changes: 21 additions & 0 deletions integration/clover/src/app/app.module.ts
@@ -0,0 +1,21 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RendererModule, TransferHttpCacheModule } from '@nguniversal/common/clover';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'hlw' }),
RendererModule.forRoot(),
TransferHttpCacheModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Empty file.
3 changes: 3 additions & 0 deletions integration/clover/src/environments/environment.prod.ts
@@ -0,0 +1,3 @@
export const environment = {
production: true
};
16 changes: 16 additions & 0 deletions integration/clover/src/environments/environment.ts
@@ -0,0 +1,16 @@
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

export const environment = {
production: false
};

/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
Binary file added integration/clover/src/favicon.ico
Binary file not shown.
13 changes: 13 additions & 0 deletions integration/clover/src/index.html
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ExpressEngineIvy</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
12 changes: 12 additions & 0 deletions integration/clover/src/main.ts
@@ -0,0 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
63 changes: 63 additions & 0 deletions integration/clover/src/polyfills.ts
@@ -0,0 +1,63 @@
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/

/***************************************************************************************************
* BROWSER POLYFILLS
*/

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.

/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.

/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags.ts';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/

/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.


/***************************************************************************************************
* APPLICATION IMPORTS
*/
4 changes: 4 additions & 0 deletions integration/clover/src/styles.css
@@ -0,0 +1,4 @@
/* You can add global styles to this file, and also import other style files */
.foo {
color: red;
}
20 changes: 20 additions & 0 deletions integration/clover/src/test.ts
@@ -0,0 +1,20 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
27 changes: 27 additions & 0 deletions integration/clover/test.js
@@ -0,0 +1,27 @@
const { Engine } = require('@nguniversal/common/clover/server');
const { join } = require('path');
const { format } = require('url');

const DIST = join(__dirname, 'dist/clover/browser');

const ssr = new Engine();
ssr.render({
publicPath: DIST,
url: format({
protocol: 'http',
host: 'localhost:8000',
pathname: '',
}),
})
.then(html => {
if (html.includes('Hello world')) {
console.log(`Response contained "Hello world"`)
} else {
console.log(html);
throw new Error(`Response didn't include "Hello world"`);
}
})
.catch(err => {
console.error(err);
process.exit(1);
});
14 changes: 14 additions & 0 deletions integration/clover/tsconfig.app.json
@@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}

1 comment on commit c4b7be3

@joelvicenteDimatur
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks very promising! My company has an ecommerce website and we would GREATLY benefit with these changes. I'm really looking forward to try it!

Please sign in to comment.