スクリーンショット_2019-10-02_16

Angular UniversalアプリケーションをサブディレクトリURLで動かす

環境

- Angular: 7.2.11
- Angular CLI: 7.3.7
- @nguniversal/express-engine: 7.1.1

やりたいこと

http://localhost:4000/app でAngular Universalアプリケーションを動かす

やったこと、つまづいたところ

1.  公式の手順通りにSSR設定を追加

ng add @nguniversal/express-engine --clientProject angular.io-example

package.jsonに以下のコマンドが追加される

・・・
"scripts": {
  ・・・
  "build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
  "build:client-and-server-bundles": "ng build --prod && ng run my-app:server:production",
  "compile:server": "webpack --config webpack.server.config.js --progress --colors",
  "serve:ssr": "node dist/server",
・・・

2.  サブディレクトリURLで動かすために、ビルド時の引数にbase-hrefを追加

"build:client-and-server-bundles": "ng build --prod --base-href=/app/ && ng run my-app:server:production",

3. このまま公式の手順通りにビルド&実行する `npm run build:ssr && npm run serve:ssr` とエラー
index.htmlはappディレクトリ下のjs/cssファイルを取りに行くけど、dist/browser以下にappディレクトリはない…

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
Uncaught SyntaxError: Unexpected token '<'

解消方法

1. outputPathをdist/browser/appに変更
angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "migiude-fe": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/browser/app",

2. ビルドする

npm run build:ssr

3. index.htmlをdist/browser下に移動

mv dist/browser/app/index.html dist/browser/index.html

4. 実行

npm run serve:ssr

これでいけます🎉🎉🎉

この記事が気に入ったらサポートをしてみませんか?