|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +import { DirEntry, Rule, chain } from '@angular-devkit/schematics'; |
| 10 | +import { addDependency } from '../../utility'; |
| 11 | +import { removePackageJsonDependency } from '../../utility/dependencies'; |
| 12 | +import { latestVersions } from '../../utility/latest-versions'; |
| 13 | +import { allTargetOptions, getWorkspace } from '../../utility/workspace'; |
| 14 | +import { Builders, ProjectType } from '../../utility/workspace-models'; |
| 15 | + |
| 16 | +function* visit(directory: DirEntry): IterableIterator<[fileName: string, contents: string]> { |
| 17 | + for (const path of directory.subfiles) { |
| 18 | + if (path.endsWith('.ts') && !path.endsWith('.d.ts')) { |
| 19 | + const entry = directory.file(path); |
| 20 | + if (entry) { |
| 21 | + const content = entry.content; |
| 22 | + if (content.includes('@nguniversal/')) { |
| 23 | + // Only need to rename the import so we can just string replacements. |
| 24 | + yield [entry.path, content.toString()]; |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + for (const path of directory.subdirs) { |
| 31 | + if (path === 'node_modules' || path.startsWith('.')) { |
| 32 | + continue; |
| 33 | + } |
| 34 | + |
| 35 | + yield* visit(directory.dir(path)); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Regexp to match Universal packages. |
| 41 | + * @nguniversal/common/engine |
| 42 | + * @nguniversal/common |
| 43 | + * @nguniversal/express-engine |
| 44 | + **/ |
| 45 | +const NGUNIVERSAL_PACKAGE_REGEXP = /@nguniversal\/(common(\/engine)?|express-engine)/g; |
| 46 | + |
| 47 | +export default function (): Rule { |
| 48 | + return chain([ |
| 49 | + async (tree) => { |
| 50 | + // Replace server file. |
| 51 | + const workspace = await getWorkspace(tree); |
| 52 | + for (const [, project] of workspace.projects) { |
| 53 | + if (project.extensions.projectType !== ProjectType.Application) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + |
| 57 | + const serverMainFiles = new Map<string /** Main Path */, string /** Output Path */>(); |
| 58 | + for (const [, target] of project.targets) { |
| 59 | + if (target.builder !== Builders.Server) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + |
| 63 | + const outputPath = project.targets.get('build')?.options?.outputPath; |
| 64 | + |
| 65 | + for (const [, { main }] of allTargetOptions(target, false)) { |
| 66 | + if ( |
| 67 | + typeof main === 'string' && |
| 68 | + typeof outputPath === 'string' && |
| 69 | + tree.readText(main).includes('ngExpressEngine') |
| 70 | + ) { |
| 71 | + serverMainFiles.set(main, outputPath); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + // Replace server file |
| 77 | + for (const [path, outputPath] of serverMainFiles.entries()) { |
| 78 | + tree.rename(path, path + '.bak'); |
| 79 | + tree.create(path, getServerFileContents(outputPath)); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + // Replace all import specifiers in all files. |
| 84 | + for (const file of visit(tree.root)) { |
| 85 | + const [path, content] = file; |
| 86 | + tree.overwrite(path, content.replaceAll(NGUNIVERSAL_PACKAGE_REGEXP, '@angular/ssr')); |
| 87 | + } |
| 88 | + |
| 89 | + // Remove universal packages from deps. |
| 90 | + removePackageJsonDependency(tree, '@nguniversal/express-engine'); |
| 91 | + removePackageJsonDependency(tree, '@nguniversal/common'); |
| 92 | + }, |
| 93 | + addDependency('@angular/ssr', latestVersions.Angular), |
| 94 | + ]); |
| 95 | +} |
| 96 | + |
| 97 | +function getServerFileContents(outputPath: string): string { |
| 98 | + return ` |
| 99 | +import 'zone.js/node'; |
| 100 | +
|
| 101 | +import { APP_BASE_HREF } from '@angular/common'; |
| 102 | +import { CommonEngine } from '@angular/ssr'; |
| 103 | +import * as express from 'express'; |
| 104 | +import { existsSync } from 'node:fs'; |
| 105 | +import { join } from 'node:path'; |
| 106 | +import bootstrap from './src/main.server'; |
| 107 | +
|
| 108 | +// The Express app is exported so that it can be used by serverless Functions. |
| 109 | +export function app(): express.Express { |
| 110 | + const server = express(); |
| 111 | + const distFolder = join(process.cwd(), '${outputPath}'); |
| 112 | + const indexHtml = existsSync(join(distFolder, 'index.original.html')) |
| 113 | + ? join(distFolder, 'index.original.html') |
| 114 | + : join(distFolder, 'index.html'); |
| 115 | +
|
| 116 | + const commonEngine = new CommonEngine(); |
| 117 | +
|
| 118 | + server.set('view engine', 'html'); |
| 119 | + server.set('views', distFolder); |
| 120 | +
|
| 121 | + // Example Express Rest API endpoints |
| 122 | + // server.get('/api/**', (req, res) => { }); |
| 123 | + // Serve static files from /browser |
| 124 | + server.get('*.*', express.static(distFolder, { |
| 125 | + maxAge: '1y' |
| 126 | + })); |
| 127 | +
|
| 128 | + // All regular routes use the Angular engine |
| 129 | + server.get('*', (req, res, next) => { |
| 130 | + commonEngine |
| 131 | + .render({ |
| 132 | + bootstrap, |
| 133 | + documentFilePath: indexHtml, |
| 134 | + url: req.originalUrl, |
| 135 | + publicPath: distFolder, |
| 136 | + providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }], |
| 137 | + }) |
| 138 | + .then((html) => res.send(html)) |
| 139 | + .catch((err) => next(err)); |
| 140 | + }); |
| 141 | +
|
| 142 | + return server; |
| 143 | +} |
| 144 | +
|
| 145 | +function run(): void { |
| 146 | + const port = process.env['PORT'] || 4000; |
| 147 | +
|
| 148 | + // Start up the Node server |
| 149 | + const server = app(); |
| 150 | + server.listen(port, () => { |
| 151 | + console.log(\`Node Express server listening on http://localhost:\${port}\`); |
| 152 | + }); |
| 153 | +} |
| 154 | +
|
| 155 | +// Webpack will replace 'require' with '__webpack_require__' |
| 156 | +// '__non_webpack_require__' is a proxy to Node 'require' |
| 157 | +// The below code is to ensure that the server is run only when not requiring the bundle. |
| 158 | +declare const __non_webpack_require__: NodeRequire; |
| 159 | +const mainModule = __non_webpack_require__.main; |
| 160 | +const moduleFilename = mainModule && mainModule.filename || ''; |
| 161 | +if (moduleFilename === __filename || moduleFilename.includes('iisnode')) { |
| 162 | + run(); |
| 163 | +} |
| 164 | +
|
| 165 | +export default bootstrap; |
| 166 | +`; |
| 167 | +} |
0 commit comments