Skip to content
This repository has been archived by the owner on Jan 30, 2024. It is now read-only.

fix: ssr exception in runtime #19

Merged
merged 2 commits into from
Nov 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ngx-sticky-demo",
"outputPath": "dist/browser",
dianjuar marked this conversation as resolved.
Show resolved Hide resolved
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
Expand Down Expand Up @@ -103,6 +103,24 @@
"**/node_modules/**"
]
}
},
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/server",
"main": "src/main.server.ts",
"tsConfig": "src/tsconfig.server.json"
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
}
}
},
Expand Down
21 changes: 16 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
"e2e": "ng e2e",
"serve:development-compilation": "npm run sticky:build && npm run build && npm run serve:compilation",
"serve:production-compilation": "npm run sticky:build-prod && npm run build:prod && npm run serve:compilation",
"serve:compilation": "angular-http-server -p 8080 --path './dist/ngx-sticky-demo/'",
"deploy-gh-pages": "npm run build:prod -- --base-href 'https://bikecoders.github.io/ngx-sticky/' && angular-cli-ghpages --repo=https://[email protected]/bikecoders/ngx-sticky.git --dir=dist/ngx-sticky-demo --branch=gh-pages --name='bikecoders' --email='[email protected]'",
"serve:compilation": "angular-http-server -p 8080 --path './dist/browser/'",
"deploy-gh-pages": "npm run build:prod -- --base-href 'https://bikecoders.github.io/ngx-sticky/' && angular-cli-ghpages --repo=https://[email protected]/bikecoders/ngx-sticky.git --dir=dist/browser --branch=gh-pages --name='bikecoders' --email='[email protected]'",
"sticky:build": "ng build sticky-directive",
"sticky:build-prod": "ng build sticky-directive --prod",
"sticky:publish": "npm run sticky:build-prod && npm run sticky:publish:copy-readme && npm run sticky:publish:copy-licence && cd dist/sticky-directive && npm publish",
Expand All @@ -27,7 +27,11 @@
"sticky:create-version": "cd projects/sticky-directive && mkdir -p .git && npm version",
"sticky:create-version:patch": "npm run sticky:create-version -- patch",
"sticky:create-version:minor": "npm run sticky:create-version -- minor",
"sticky:create-version:major": "npm run sticky:create-version -- major"
"sticky:create-version:major": "npm run sticky:create-version -- major",
"compile:server": "webpack --config webpack.server.config.js --progress --colors",
"serve:ssr": "node dist/server",
"build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
"build:client-and-server-bundles": "ng build --prod && ng run ngx-sticky-demo:server:production"
},
"private": true,
"dependencies": {
Expand All @@ -39,9 +43,13 @@
"@angular/http": "~7.2.1",
"@angular/platform-browser": "~7.2.1",
"@angular/platform-browser-dynamic": "~7.2.1",
"@angular/platform-server": "~7.2.1",
"@angular/router": "~7.2.1",
"@nguniversal/express-engine": "~7.1.1",
"@nguniversal/module-map-ngfactory-loader": "~7.1.1",
"core-js": "^2.6.2",
"intersection-observer": "^0.5.1",
"express": "^4.15.2",
"intersection-observer": "^0.7.0",
dianjuar marked this conversation as resolved.
Show resolved Hide resolved
"ngx-sticky-directive": "latest",
"rxjs": "~6.3.3",
"zone.js": "~0.8.28"
Expand All @@ -52,6 +60,7 @@
"@angular/cli": "~7.2.2",
"@angular/compiler-cli": "~7.2.1",
"@angular/language-service": "~7.2.1",
"@types/express": "^4.17.2",
"@types/jasmine": "~3.3.7",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^11.13.0",
Expand All @@ -71,10 +80,12 @@
"ng-packagr": "^4.6.0",
"protractor": "~5.4.0",
"sonar-scanner": "^3.1.0",
"ts-loader": "^5.2.0",
"ts-node": "~7.0.0",
"tsickle": ">=0.29.0",
"tslib": "^1.9.0",
"tslint": "~5.12.1",
"typescript": "~3.2.4"
"typescript": "~3.2.4",
"webpack-cli": "^3.1.0"
}
}
4 changes: 2 additions & 2 deletions projects/sticky-directive/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@
"peerDependencies": {
"@angular/common": "^7.2.1",
"@angular/core": "^7.2.1",
"intersection-observer": "^0.5.1"
"intersection-observer": "^0.7.0"
},
"dependencies": {
"intersection-observer": "^0.5.1"
"intersection-observer": "^0.7.0"
},
"homepage": "https://github.com/bikecoders/ngx-sticky#readme",
"readmeFilename": "README.md"
Expand Down
18 changes: 13 additions & 5 deletions projects/sticky-directive/src/lib/sticky.directive.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Directive, OnInit, ElementRef, Input, AfterViewInit } from '@angular/core';
import { Directive, OnInit, ElementRef, Input, AfterViewInit, Inject, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';

/**
* This directive puts a css class in a sticky element to improve usability.
* To understand how it works I highly recommend to read the article that was used to made this.
* Here you can understand better the architecture:
* https://developers.google.com/web/updates/2017/09/sticky-headers
*/
/** @dynamic */
@Directive({
selector: '[ngxSticky]'
})
Expand Down Expand Up @@ -80,7 +82,11 @@ export class StickyDirective implements OnInit, AfterViewInit {
*/
private sentinel: HTMLElement;

constructor(private stickyElement: ElementRef) {
constructor(
@Inject(DOCUMENT) private document: Document,
@Inject(PLATFORM_ID) private platformId: object,
private stickyElement: ElementRef,
) {
// Import the Intersection Observer polyfill
require('intersection-observer');
}
Expand All @@ -91,15 +97,17 @@ export class StickyDirective implements OnInit, AfterViewInit {

ngAfterViewInit() {
this.putSentinel();
this.setObserver();
if (isPlatformBrowser(this.platformId)) {
this.setObserver();
}
}

/**
* Transform if needed into HTMLElement a value given to be set in a property
*/
private setHTMLElement(prop: string, value: string | ElementRef | HTMLElement): void {
if (typeof value === 'string') {
this[prop] = document.getElementById(value);
this[prop] = this.document.getElementById(value);
} else if (value instanceof ElementRef) {
this[prop] = value.nativeElement;
} else {
Expand Down Expand Up @@ -163,7 +171,7 @@ export class StickyDirective implements OnInit, AfterViewInit {
* Generates the sentinel element with the necessary styles
*/
private generateSentinelElement(): HTMLElement {
const sentinelEl = document.createElement('div');
const sentinelEl = this.document.createElement('div');
sentinelEl.style.height = '50px';
sentinelEl.style.width = '100%';
sentinelEl.style.position = 'absolute';
Expand Down
49 changes: 49 additions & 0 deletions server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import 'zone.js/dist/zone-node';
import {enableProdMode} from '@angular/core';
// Express Engine
import {ngExpressEngine} from '@nguniversal/express-engine';
// Import module map for lazy loading
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';

import * as express from 'express';
import {join} from 'path';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});

// Start up the Node server
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
});
2 changes: 1 addition & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { StickyDirectiveModule } from 'ngx-sticky-directive';
AppComponent
],
imports: [
BrowserModule,
BrowserModule.withServerTransition({ appId: 'serverApp' }),
StickyDirectiveModule
],
providers: [],
Expand Down
16 changes: 16 additions & 0 deletions src/app/app.server.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';

@NgModule({
imports: [
AppModule,
ServerModule,
ModuleMapLoaderModule,
],
bootstrap: [AppComponent],
})
export class AppServerModule {}
9 changes: 9 additions & 0 deletions src/main.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { enableProdMode } from '@angular/core';

import { environment } from './environments/environment';

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

export { AppServerModule } from './app/app.server.module';
4 changes: 3 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
});
10 changes: 10 additions & 0 deletions src/tsconfig.server.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"outDir": "../out-tsc/app-server",
"baseUrl": "."
},
"angularCompilerOptions": {
"entryModule": "app/app.server.module#AppServerModule"
}
}
47 changes: 47 additions & 0 deletions webpack.server.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Work around for https://github.com/angular/angular-cli/issues/7200

const path = require('path');
const webpack = require('webpack');

module.exports = {
mode: 'none',
entry: {
// This is our Express server for Dynamic universal
server: './server.ts'
},
target: 'node',
resolve: { extensions: ['.ts', '.js'] },
optimization: {
minimize: false
},
output: {
// Puts the output at the root of the dist folder
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{ test: /\.ts$/, loader: 'ts-loader' },
{
// Mark files inside `@angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
test: /(\\|\/)@angular(\\|\/)core(\\|\/).+\.js$/,
parser: { system: true },
},
]
},
plugins: [
new webpack.ContextReplacementPlugin(
// fixes WARNING Critical dependency: the request of a dependency is an expression
/(.+)?angular(\\|\/)core(.+)?/,
path.join(__dirname, 'src'), // location of your src
{} // a map of your routes
),
new webpack.ContextReplacementPlugin(
// fixes WARNING Critical dependency: the request of a dependency is an expression
/(.+)?express(\\|\/)(.+)?/,
path.join(__dirname, 'src'),
{}
)
]
};
Loading