カテゴリー
【Angularの新しいSSR環境】「Angular Universal」から「@angular/ssr」へのマイグレーションガイド
※ 当ページには【広告/PR】を含む場合があります。
2024/08/16
UniversalをAngular/SSRへ巻き上げる
$ ng new --ssr
$ npm run build && npm run serve:ssr:[アプリケーション名]
#クライアントサイドのビルド
$ ng build --configuration production
#次段でサーバーサイドのビルド(SSRのみ/プレレンダリングは別)
$ ng run [アプリケーション名]:server:production
v16からv17への移行作業
@nguniversal
@angular/ssr
@angular/ssr
ng new --ssr
ng new --ssr
1. ビルドシステムの一新:
Webpack(@angular-devkit/build-angular:browser)から
esbuild(@angular-devkit/build-angular:application)へ移行
2. コンポーネントのスタンドアローン対応:
全コンポーネントをNgModuleの削除などstandaloneへ移行
server.ts
ビルドシステムを「@angular-devkit/build-angular:application」に移行する
package.json
~17.0.0
@angular
typescript
rxjs
zone.js
{
//...中略
"dependencies": {
"@angular/animations": "~17.0.0",
"@angular/common": "~17.0.0",
"@angular/compiler": "~17.0.0",
"@angular/core": "~17.0.0",
"@angular/forms": "~17.0.0",
"@angular/platform-browser": "~17.0.0",
"@angular/platform-browser-dynamic": "~17.0.0",
"@angular/platform-server": "~17.0.0",
"@angular/router": "~17.0.0",
"rxjs": "^7.4.0",
"zone.js": "~0.14.0",
//...
},
"devDependencies": {
"@angular-devkit/build-angular": "~17.0.0",
"@angular/cli": "~17.0.0",
"@angular/compiler-cli": "~17.0.0",
"typescript": "~5.2.0",
//...
}
}
package.json
$ rm -rf yarn.lock node_modules
$ yarn install
angular.jsonを手動でリニューアル
angular.json
angular.json
architect/build
architect/serve
//...
"projects": {
"プロジェクト名": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
//👇ビルダーをbrowserからapplicationへ変える
"builder": "@angular-devkit/build-angular:application",
"options": {
//👇Universal以前はdist/プロジェクト名/browserだったものから変える
"outputPath": "dist/プロジェクト名",
"index": "src/index.html",
"browser": "src/main.ts",
//👇polyfills.tsファイルの指定ではなく、個別ファイル指定となった
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
],
"styles": [
"src/styles.scss"
],
"scripts": [],
//👇以下のserver/preprender/ssrの項目が新設
"server": "src/main.server.ts",
"prerender": {
"discoverRoutes": true,
},
"ssr": {
"entry": "server.ts"
}
},
//👇configurationsからbuildOptimizer/vendorChunk/commonChunkが不要になった
"configurations": {
"production": {
"optimization": true,
"outputHashing": "none",
"sourceMap": false,
"namedChunks": true,
"extractLicenses": false,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "15kb",
"maximumError": "18kb"
}
]
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
//👇browserTargetからbuildTargetの名前に変更
"buildTarget": "プロジェクト名:build:production"
},
"development": {
//👇browserTargetからbuildTargetの名前に変更
"buildTarget": "プロジェクト名:build:development"
},
"defaultConfiguration": "development"
}
},
//...
}
architect/server(@angular-devkit/build-angular:server)
architect/serve-ssr(@nguniversal/builders:ssr-dev-server)
@angular-devkit/build-angular:application
polyfills.ts
server
tsconfig.app.json
files
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": ["node"],
"lib": [
"esnext",
"dom"
]
},
"files": [
"src/main.ts",
//👇サーバーサイドのアプリケーションもここに追加
"src/main.server.ts",
"server.ts"
],
"include": [
"src/**/*.d.ts"
]
}
tsconfig.server.json
プロジェクトコードをスタンドアローン化する
*.module.ts
*.module.ts
$ ng generate @angular/core:standalone
? Choose the type of migration: (Use arrow keys)
❯ Convert all components, directives and pipes to standalone
Remove unnecessary NgModule classes
Bootstrap the application using standalone APIs
$ ng generate @angular/core:standalone
? Choose the type of migration: Convert all components, directives and pipes to standalone
? Which path in your project should be migrated? ./
🎉 Automated migration step has finished! 🎉
IMPORTANT! Please verify manually that your application builds and behaves as expected.
See https://angular.dev/reference/migrations/standalone for more information.
UPDATE src/app/misc/components/thankyou/thankyou.component.ts (604 bytes)
UPDATE src/app/blog/blog-page/blog-page.component.ts (13522 bytes)
#...中略
UPDATE src/app/blog/blog.module.ts (2574 bytes)
UPDATE src/app/top-page/top-page.module.ts (2831 bytes)
UPDATE src/app/misc/notfound.module.ts (586 bytes)
./
standalone: true
imports
$ ng generate @angular/core:standalone
? Choose the type of migration: Remove unnecessary NgModule classes
? Which path in your project should be migrated? ./
🎉 Automated migration step has finished! 🎉
IMPORTANT! Please verify manually that your application builds and behaves as expected.
See https://angular.dev/reference/migrations/standalone for more information.
Nothing to be done.
bootstrap
$ ng generate @angular/core:standalone
? Choose the type of migration: Bootstrap the application using standalone APIs
? Which path in your project should be migrated? ./
🎉 Automated migration step has finished! 🎉
IMPORTANT! Please verify manually that your application builds and behaves as expected.
See https://angular.dev/reference/migrations/standalone for more information.
DELETE src/app/app.module.ts
UPDATE src/main.ts (3273 bytes)
app.component.ts
main.ts
app.module.ts
app.server.module.ts
standalone
imports
main.tsからmoduleの一切を削る
main.ts
main.ts
import { CommonModule } from '@angular/common';
import { enableProdMode, importProvidersFrom } from '@angular/core';
import { BrowserModule, bootstrapApplication } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import { withInterceptorsFromDi, provideHttpClient } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app/app.component';
import { HogeModule } from './app/hoge.module';
import { PiyoModule } from './app/piyo.module';
import { AppRoutingModule } from './app/app-routing.module';
document.addEventListener('DOMContentLoaded', () => {
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(
BrowserModule.withServerTransition({ appId: 'プロジェクト名' }), AppRoutingModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
HogeModule,
PiyoModule
),
provideHttpClient(withInterceptorsFromDi()),
provideAnimations()
]
}).catch(err => console.error(err));
});
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
app.component.ts
app.component.ts
import { Component } from '@angular/core';
//👇スタンドアローン化したルーターアウトレットを使う準備
import { RouterModule, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`,
//👇追加
standalone: true,
imports: [RouterOutlet, RouterModule]
})
export class AppComponent { }
<app-root>
app-routing.module.ts --> app.routes.ts
「app-routing.module.ts」
「app.routes.ts」
import { Routes } from '@angular/router';
import { HomeComponent } from './components/home.component';
import { PageNotFoundComponent } from './components/page-not-found.component';
import { ThankyouComponent } from './components/thankyou.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'error', component: PageNotFoundComponent },
{ path: 'confirmation', component: ThankyouComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', redirectTo: '/error', pathMatch: 'full' }
];
app.config.tsとapp.config.server.ts
「app.config.ts」
「app.config.server.ts」
app.config.ts
app.module.ts
app.config.server.ts
app.server.module.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideAnimations(),
provideHttpClient(),
]
};
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
UniversalをAngular/SSRへ移行する
warning " > @nguniversal/common@16.1.3" has incorrect peer dependency "@angular/common@^16.0.0 || ^16.1.0-next.0".
warning " > @nguniversal/common@16.1.3" has incorrect peer dependency "@angular/core@^16.0.0 || ^16.1.0-next.0".
warning " > @nguniversal/express-engine@16.1.3" has incorrect peer dependency "@angular/common@^16.0.0 || ^16.1.0-next.0".
warning " > @nguniversal/express-engine@16.1.3" has incorrect peer dependency "@angular/core@^16.0.0 || ^16.1.0-next.0".
warning " > @nguniversal/builders@16.1.3" has incorrect peer dependency "@angular-devkit/build-angular@^16.0.0 || ^16.1.0-next.0".
$ yarn remove @nguniversal/common @nguniversal/express-engine @nguniversal/builders
$ yarn add -D @angular/ssr@^17.0.0
my-app
|-- server.ts #サーバーアプリケーション
└── src
|-- app
| └── app.config.server.ts #サーバーアプリケーション設定
└── main.server.ts #サーバーのブートストラップ
app.module.ts + app.server.module.ts
app.config.ts + app.config.server.ts
app.config.ts
app.config.server.ts
app.config.tsのHttpClientモジュール対応
app.config.ts
ng new --ssr
app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideAnimations()
]
};
ERROR Error [NullInjectorError]: R3InjectorError(_ToppageModule)[_SubpageResolver -> _ProvisioningArticleService -> _HttpClient -> _HttpClient -> _HttpClient]:
NullInjectorError: No provider for _HttpClient!
at NullInjector.get (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:5627:27)
at R3Injector.get (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:6070:33)
at R3Injector.get (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:6070:33)
at R3Injector.get (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:6070:33)
at injectInjectorOnly (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:912:40)
at Module.ɵɵinject (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:918:42)
at Object.ProvisioningArticleService_Factory (/usr/src/app/workspace/src/app/service/provisioning-article.service.ts:16:40)
at eval (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:6192:43)
at runInInjectorProfilerContext (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:868:9)
at R3Injector.hydrate (/usr/src/app/workspace/node_modules/@angular/core/fesm2022/core.mjs:6191:17) {
ngTempTokenPath: null,
ngTokenPath: [
'_SubpageResolver',
'_ProvisioningArticleService',
'_HttpClient',
'_HttpClient',
'_HttpClient'
]
}
HttpClient
HttpClientModule
provideClientHydration
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
//👇追加
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideAnimations(),
provideHttpClient(),
]
};
main.server.ts
main.server.ts
import '@angular/platform-server/init';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
global['requestAnimationFrame'] = (callback: any) => {
let lastTime = 0;
const currTime = new Date().getTime();
const timeToCall = Math.max(0, 16 - (currTime - lastTime));
const id: any = setTimeout(() => {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
global['cancelAnimationFrame'] = (id) => {
clearTimeout(id);
};
} else {
console.log('[Server/ExpressNodejs] main.server.ts is enabled Development mode.');
}
export { AppServerModule } from './app/app.server.module';
export { renderModule } from '@angular/platform-server';
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;
server.ts
server.ts
import {APP_BASE_HREF} from '@angular/common';
import {CommonEngine} from '@angular/ssr';
import express from 'express';
import {fileURLToPath} from 'node:url';
import {dirname, join, resolve} from 'node:path';
import bootstrap from './src/main.server';
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', browserDistFolder);
server.get('/api/**', (req, res) => {
res.status(404).send('data requests are not yet supported');
});
server.get(
'*.*',
express.static(browserDistFolder, {
maxAge: '1y',
}),
);
server.get('*', (req, res, next) => {
const {protocol, originalUrl, baseUrl, headers} = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{provide: APP_BASE_HREF, useValue: req.baseUrl}],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
export * from './src/main.server';
ng new --ssr
server.ts
run
local.ts
ts-node
import { app } from './dist/プロジェクト名/server/server.mjs';
function run(): void {
const port = process.env.PORT || process.env.NG_DEV_PORT;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
run();
ビルドして動作確認
$ ng build --configuration production
dist
dist/
└── [プロジェクト名]
├── browser
├── prerendered-routes.json
└── server
├── #...中略
├── main.server.mjs
└── server.mjs
ts-node
tsx
$ node --import tsx ./local.ts
その他細かい修正
Sassでのnode_modulesからのインポート
@import '~katex/dist/katex.min.css';
build
stylePreprocessorOptions
///,
"styles": [
"src/styles.scss"
],
"stylePreprocessorOptions": {
"includePaths": [
"../node_modules/katex/dist"
]
},
///
// @import '~katex/dist/katex.min.css';
//👇node_modulesまでの相対パスに変える
@import '../node_modules/katex/dist/katex.min.css';
まとめ
記事を書いた人
ナンデモ系エンジニア
主にAngularでフロントエンド開発することが多いです。 開発環境はLinuxメインで進めているので、シェルコマンドも多用しております。 コツコツとプログラミングするのが好きな人間です。
カテゴリー