Igor Soloydenko
Igor Soloydenko

Reputation: 11825

"Error: In this configuration Angular requires Zone.js" when trying to set up a platform-server

Still trying to set up a platform server and render my module with a custom renderer (which I don't have implemented yet).

Issues

Main Code

export function createCompiler(compilerFactory: CompilerFactory) {
  return compilerFactory.createCompiler();
}

async function generate<M>(moduleType: Type<M>) {
  try {
    const extraProviders: StaticProvider[] = [
      { provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory] },
    ];
    const platformRef = platformDynamicServer(extraProviders);
    const moduleRef = await platformRef
      .bootstrapModule(
        moduleType,
        {
          providers: [ { provide: ResourceLoader, useValue: new ResourceLoaderImpl(`src\\app`), deps: [ ] }, ],
        });
    
    const appComponent = moduleRef.injector.get(AppComponent);
    
    console.info(appComponent.title.toString());
  } catch (error) {
    throw new Error(error.toString());
  }
}

generate(AppModule)
  .then(message => console.info({ message }))
  .catch(error => console.error({ error }));

Custom Resource Loader

@Injectable()
export class ResourceLoaderImpl extends ResourceLoader {
  constructor(private _cwd: string) {
    super();
  }

  get(resourceFileName: string): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      glob(`**/${resourceFileName}`, { cwd: this._cwd, }, (globError, matches) => {
        if (globError) reject(globError);
        else
          readFile(
            path.join(this._cwd, matches[0]),
            (readFileError, data) => {
              if (readFileError) reject(readFileError);
              else resolve(data.toString());
            }
          );
      });
    });
  }
}

Imports

import { ResourceLoader } from '@angular/compiler';
import { Compiler, CompilerFactory, Injectable, StaticProvider, Type } from '@angular/core';
import { platformDynamicServer } from '@angular/platform-server';
import { readFile } from 'fs';
import * as glob from 'glob';
import * as path from 'path';
import { AppComponent } from './app/app.component';
import { AppModule } from './app/app.module';

Upvotes: 7

Views: 12027

Answers (1)

Igor Soloydenko
Igor Soloydenko

Reputation: 11825

Fixed with statically importing zone.js:

import 'zone.js';
import 'zone.js/dist/long-stack-trace-zone.js';

Upvotes: 7

Related Questions