Angular 8服务端渲染

时间:2019-11-11 19:58:12

标签: angular angular7 angular8

我在服务器端渲染中遇到了一个问题,即角度构建成功而不是错误,但是我遇到了这个错误 (节点:6950)[DEP0005] DeprecationWarning:由于安全性和可用性问题,不建议使用Buffer()。 server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { enableProdMode } from '@angular/core';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as compression from 'compression';
import * as express from 'express';
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');
const fs = require('fs');
const path = require('path');
const filterEnv = require('filter-env');
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';
enableProdMode();
const dotenv = require('dotenv');
dotenv.config();
const config = filterEnv(/(BB_\w+)/, {json: true, freeze: true});

const PORT = process.env.BB_PORT || 8000;

// Provide support for window on the server
const domino = require('domino');
const template = fs.readFileSync(path.join('dist/browser', 'index.html')).toString();
const fetch = require('node-fetch');
const win = domino.createWindow(template);

win.fetch = fetch;
global['window'] = win;
Object.defineProperty(win.document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true
    };
  },
});
global['document'] = win.document;
global['CSS'] = null;
// global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;
global['Prism'] = null;

const app = express();

// Config renderer
try {
  app.engine('html', (_, options, callback) => {
    const engine = ngExpressEngine({
      bootstrap: AppServerModuleNgFactory,
      providers: [
        provideModuleMap(LAZY_MODULE_MAP),
        { provide: 'REQUEST', useFactory: () => options.req, deps: [] },
        { provide: 'CONFIG', useFactory: () => config, deps: [] }
      ]
    });
    engine(_, options, callback);
  });
} catch (e) {
  console.log('error', 'there is sonme issue defining app engine ' + e);
}

// configs
app.enable('etag');

// Middleware
app.use(compression());
app.set('view engine', 'html');
app.set('views', 'dist/browser');
app.set('view cache', true);
app.use('/', express.static('dist/browser', { index: false, maxAge: 30 * 86400000 }));

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

app.get('/env', (req, res) => {
  res.json(process.env);
})
  
app.listen(PORT,() => {
  console.log(`we are serving the site for you at http://localhost:${PORT}!`);
});

// angular json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "aumet": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/web.config",
              "src/firebase-messaging-sw.js",
              "src/manifest.json"
            ],
            "styles": [
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",
              "./node_modules/intl-tel-input/build/css/intlTelInput.css",
              "./node_modules/ngx-lightbox/lightbox.css",
              "src/assets/css/animations-extended.min.css",
              "src/styles.scss"
            ],
            "scripts": [
              "./node_modules/bootstrap/dist/js/bootstrap.min.js",
              "src/assets/js/venobox.min.js",
              "src/assets/js/wow.js",
              "src/assets/js/custom.js",
              {
                "input": "node_modules/document-register-element/build/document-register-element.js"
              }
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "aumet:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "aumet:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "aumet:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "aumet:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "aumet:serve:production"
            }
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "src/main.server.ts",
            "tsConfig": "tsconfig.server.json"
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "sourceMap": false,
              "optimization": {
                "scripts": false,
                "styles": true
              }
            }
          }
        }
      }
    }
  },
  "defaultProject": "aumet"
}

// package.json

{
  "name": "aumet",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
    "serve:ssr": "node dist/server.js",
    "build:client-and-server-bundles": "node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng build  --prod --aot && ng run aumet:server:production",
    "webpack:server": "webpack --config webpack.server.config.js --progress --colors",
    "start-ssr": "npm run build:ssr && npm run serve:ssr"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.2.7",
    "@angular/cdk": "~8.2.3",
    "@angular/common": "~8.2.7",
    "@angular/compiler": "~8.2.7",
    "@angular/core": "~8.2.7",
    "@angular/fire": "^5.2.1",
    "@angular/forms": "~8.2.7",
    "@angular/material": "^8.2.3",
    "@angular/material-moment-adapter": "^8.2.3",
    "@angular/platform-browser": "~8.2.7",
    "@angular/platform-browser-dynamic": "~8.2.7",
    "@angular/platform-server": "~8.2.7",
    "@angular/router": "~8.2.7",
    "@auth0/angular-jwt": "^3.0.1",
    "@ngu/carousel": "^1.5.5",
    "@nguniversal/express-engine": "^8.1.1",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "@nicky-lenaers/ngx-scroll-to": "^3.0.1",
    "@types/jquery": "^3.3.31",
    "@types/swiper": "^5.2.0",
    "angular2-useful-swiper": "^8.0.1-beta.1",
    "aws-sdk": "^2.568.0",
    "bootstrap": "^4.3.1",
    "compression": "^1.7.4",
    "core-js": "^3.4.0",
    "document-register-element": "^1.14.3",
    "dotenv": "^8.2.0",
    "express": "^4.15.2",
    "filter-env": "^1.1.2",
    "firebase": "^7.3.0",
    "font-awesome": "^4.7.0",
    "google-libphonenumber": "^3.2.6",
    "google-translate": "^3.0.0",
    "guid-typescript": "^1.0.9",
    "hammerjs": "^2.0.8",
    "highlight.js": "^9.16.2",
    "intl-tel-input": "^16.0.7",
    "jquery": "^3.4.1",
    "moment": "^2.24.0",
    "ng-click-outside": "^5.1.1",
    "ng-lottie": "^0.3.2",
    "ngx-bootstrap": "^5.2.0",
    "ngx-drag-scroll": "^8.0.0-beta.2",
    "ngx-gallery": "^5.10.0",
    "ngx-infinite-scroll": "^8.0.1",
    "ngx-intl-tel-input": "^2.3.1",
    "ngx-lightbox": "^2.1.1",
    "ngx-quill": "^7.3.9",
    "node-fetch": "^2.6.0",
    "node-sass": "^4.13.0",
    "popper.js": "^1.16.0",
    "pusher-js": "^5.0.2",
    "quill": "^1.3.7",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.5",
    "@angular/cli": "~8.3.5",
    "@angular/compiler-cli": "~8.2.7",
    "@angular/language-service": "~8.2.7",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-loader": "^5.2.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3",
    "webpack-cli": "^3.1.0"
  }
}

// webpack

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

module.exports = {
  mode: 'none',
  entry: {
    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'),
      {}
    )
  ]
}

// app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } 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,
    ServerTransferStateModule,
    ModuleMapLoaderModule,
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}
// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoginComponent } from './auth/login/login.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthService } from './_services';
import { JwtInterceptor } from './_helpers/jwt.interceptor';
import { ErrorInterceptor } from './_helpers/error.interceptor';
import { HttpRequest } from '@angular/common/http';
import { registrationGuard } from './_guards/registration.guard';
import { ForgetPasswordComponent } from './auth/forget-password/forget-password.component';
import { ResetPasswordComponent } from './auth/reset-password/reset-password.component';
import { DefaultHeaderModule } from './shared/default-header.module';
import { ManufacturerGuard } from './_guards/manufacturer.guard';
import { AuthGuard } from './_guards/auth.guard';
import { DistributorGuard } from './_guards/distributor.guard';
import { CurrentCountryResolveModule } from './resolversModules/current-countryResolve.module';
import { MessagesService } from './_services/messages.service';
import { AsyncPipe } from '@angular/common';
import { AngularFireModule } from '@angular/fire';
import { AngularFireMessagingModule } from '@angular/fire/messaging';
import { environment } from '../environments/environment';
import { HomeModule } from './home/home/home.module';
import { SharedModule } from './shared/shared.module';
import { TranslateModule } from './_translate/translate.module';
import { PublicGuard } from './_guards/public.guard';
import { TranslateService } from './_translate/translate.service';
import { DomainEmailComponent } from './process/common/domain-email/domain-email.component';
import { MatDialogModule } from '@angular/material';
import { SearchHeaderModule } from './search-header/search-header.module';

@NgModule({
  declarations: [AppComponent, LoginComponent, ResetPasswordComponent, ForgetPasswordComponent,    DomainEmailComponent],
  imports: [
    HomeModule,
    SearchHeaderModule,
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    AppRoutingModule,
    TranslateModule,
    DefaultHeaderModule,
    CurrentCountryResolveModule.forRoot(),
    BrowserAnimationsModule,
    HttpClientModule,
    AngularFireMessagingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    SharedModule,
    // For HTML CSS delivery from Ala'
    MatDialogModule,

  ],
  exports: [],
  providers: [
    AuthService,
    AuthGuard,
    PublicGuard,
    registrationGuard,
    ManufacturerGuard,
    DistributorGuard,
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
    MessagesService,
    AsyncPipe,
    TranslateService,
    { provide: APP_INITIALIZER, useFactory: languagesProvidorFactor, deps: [TranslateService], multi: true }
  ],
  bootstrap: [AppComponent],
  entryComponents: [DomainEmailComponent]
})
export class AppModule { }

export function requestFilter(request: HttpRequest<any>): boolean {
  return request.url === 'https://api2.aumet.me/api/Countries/GetCountriesWithBusinessRelation';
}
export function languagesProvidorFactor(provider: TranslateService) {
  return () => provider.load();
}

// tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true  ,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

// tsconfing.server.json

{
  "extends": "./tsconfig.app.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app-server",
    "module": "commonjs"
  },
  "files": [
    "src/main.server.ts"
  ],
  "angularCompilerOptions": {
    "entryModule": "./src/app/app.server.module#AppServerModule"
  }
}

// tsconfig.app.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [
      "node",
      "jquery"
    ]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}

我需要快速的解决方案,我已经尝试了很多事情,即使应用程序正常工作,它也是如此缓慢,无法获得所有图像,也无法为所有路径进行路由,但是我现在仍然会遇到此错误 有人可以帮我吗

0 个答案:

没有答案