Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: prerender the app at build time #239

Merged
merged 3 commits into from
Jul 20, 2024
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
10 changes: 2 additions & 8 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,12 @@
{
"files": ["*.ts", "*.tsx"],
"extends": ["plugin:@nx/typescript"],
"rules": {
"@typescript-eslint/no-extra-semi": "error",
"no-extra-semi": "off"
}
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"extends": ["plugin:@nx/javascript"],
"rules": {
"@typescript-eslint/no-extra-semi": "error",
"no-extra-semi": "off"
}
"rules": {}
},
{
"files": ["*.spec.ts", "*.spec.tsx", "*.spec.js", "*.spec.jsx"],
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
cache: 'yarn'

- run: yarn install
- run: npx nx run website:build
- run: npx nx run website:prerender

- name: Archive artifacts
uses: actions/upload-artifact@v4
Expand Down
3 changes: 1 addition & 2 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@
/dist
/coverage
/.nx/cache
/.nx/workspace-data
.angular

/.nx/workspace-data
4 changes: 0 additions & 4 deletions .prettierrc

This file was deleted.

1,232 changes: 884 additions & 348 deletions .yarn/releases/yarn-1.22.21.cjs → .yarn/releases/yarn-1.22.22.cjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .yarnrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
# yarn lockfile v1


yarn-path ".yarn/releases/yarn-1.22.21.cjs"
yarn-path ".yarn/releases/yarn-1.22.22.cjs"
19 changes: 0 additions & 19 deletions apps/website/plugins/env.js

This file was deleted.

76 changes: 70 additions & 6 deletions apps/website/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,26 @@
"tags": [],
"targets": {
"build": {
"executor": "@nx/angular:application",
"executor": "@nx/angular:webpack-browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/website",
"outputPath": "dist/apps/website/browser",
"index": "apps/website/src/index.html",
"browser": "apps/website/src/main.ts",
"main": "apps/website/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/website/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": ["apps/website/src/favicon.ico", "apps/website/src/assets"],
"assets": [
{
"glob": "**/*",
"input": "apps/website/public"
}
],
"styles": ["apps/website/src/styles.scss"],
"scripts": [],
"plugins": ["apps/website/plugins/env.js"]
"customWebpackConfig": {
"path": "apps/website/webpack.config.js"
}
},
"configurations": {
"production": {
Expand All @@ -38,9 +45,12 @@
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
Expand Down Expand Up @@ -72,6 +82,60 @@
"options": {
"jestConfig": "apps/website/jest.config.ts"
}
},
"server": {
"dependsOn": ["build"],
"executor": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/apps/website/server",
"main": "apps/website/server.ts",
"tsConfig": "apps/website/tsconfig.server.json",
"inlineStyleLanguage": "scss"
},
"configurations": {
"production": {
"outputHashing": "media"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"sourceMap": true,
"extractLicenses": false,
"vendorChunk": true
}
},
"defaultConfiguration": "production"
},
"serve-ssr": {
"executor": "@angular-devkit/build-angular:ssr-dev-server",
"configurations": {
"development": {
"browserTarget": "website:build:development",
"serverTarget": "website:server:development"
},
"production": {
"browserTarget": "website:build:production",
"serverTarget": "website:server:production"
}
},
"defaultConfiguration": "development"
},
"prerender": {
"executor": "@angular-devkit/build-angular:prerender",
"options": {
"routes": ["/"]
},
"configurations": {
"development": {
"browserTarget": "website:build:development",
"serverTarget": "website:server:development"
},
"production": {
"browserTarget": "website:build:production",
"serverTarget": "website:server:production"
}
},
"defaultConfiguration": "production"
}
}
}
File renamed without changes.
73 changes: 73 additions & 0 deletions apps/website/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import 'zone.js/node';

import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import bootstrap from './src/main.server';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), 'dist/apps/website/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html'))
? join(distFolder, 'index.original.html')
: join(distFolder, 'index.html');

const commonEngine = new CommonEngine();

server.set('view engine', 'html');
server.set('views', distFolder);

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

// All regular routes use the Angular engine
server.get('**', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;

commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: distFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});

return server;
}

function run(): void {
const port = process.env['PORT'] || 4000;

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

// 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')) {
run();
}

export default bootstrap;
Empty file.
1 change: 0 additions & 1 deletion apps/website/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,5 @@ import { RouterModule } from '@angular/router';
imports: [RouterModule],
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
export class AppComponent {}
10 changes: 10 additions & 0 deletions apps/website/src/app/app.config.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
import { provideClientHydration } from '@angular/platform-browser';

const serverConfig: ApplicationConfig = {
providers: [provideClientHydration(), provideServerRendering()],
};

export const config = mergeApplicationConfig(appConfig, serverConfig);
40 changes: 33 additions & 7 deletions apps/website/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,52 @@
import { ApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideClientHydration } from '@angular/platform-browser';

import { appRoutes } from './app.routes';
import {
CONTENTFUL_SPACE,
CONTENTFUL_ACCESS_TOKEN,
CONTENTFUL_ENVIRONMENT,
CONTENTFUL_SPACE,
} from '@valerymelou/cms/contentful';
import { WINDOW_TOKEN } from '@valerymelou/common/browser';

import { appRoutes } from './app.routes';
import { provideAnimations } from '@angular/platform-browser/animations';

export const appConfig: ApplicationConfig = {
providers: [
provideAnimations(),
provideClientHydration(),
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(appRoutes),
provideRouter(appRoutes),
{ provide: CONTENTFUL_SPACE, useValue: process.env.VM_CONTENTFUL_SPACE },
{
provide: WINDOW_TOKEN,
useFactory: () => {
if (typeof window !== 'undefined') {
return window;
}

return {
matchMedia: () => ({
removeEventListener: () => true,
addEventListener: () => true,
matches: true,
}),
location: {
origin: 'https://valerymelou.com',
href: '',
},
};
},
},
{ provide: CONTENTFUL_SPACE, useValue: process.env['VM_CONTENTFUL_SPACE'] },
{
provide: CONTENTFUL_ACCESS_TOKEN,
useValue: process.env.VM_CONTENTFUL_ACCESS_TOKEN,
useValue: process.env['VM_CONTENTFUL_ACCESS_TOKEN'],
},
{
provide: CONTENTFUL_ENVIRONMENT,
useValue: process.env.VM_CONTENTFUL_ENVIRONMENT,
useValue: process.env['VM_CONTENTFUL_ENVIRONMENT'],
},
],
};
7 changes: 7 additions & 0 deletions apps/website/src/main.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';

const bootstrap = () => bootstrapApplication(AppComponent, config);

export default bootstrap;
2 changes: 1 addition & 1 deletion apps/website/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
console.error(err),
);
3 changes: 2 additions & 1 deletion apps/website/src/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
background-color: transparent;
background-image: url('/assets/images/looper.svg');
background-repeat: no-repeat;
background-size: cover;
background-size: 50%;
background-position: right;
background-attachment: fixed;
}

Expand Down
2 changes: 1 addition & 1 deletion apps/website/tsconfig.app.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": []
"types": ["node"]
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"],
Expand Down
2 changes: 0 additions & 2 deletions apps/website/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
Expand Down
10 changes: 10 additions & 0 deletions apps/website/tsconfig.server.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"outDir": "../../out-tsc/server",
"target": "es2019",
"types": ["node"]
},
"files": ["src/main.server.ts", "server.ts"]
}
Loading