0

I'd like to start using Angular components in an existing angularjs project would like to use downgradeModule to create a hybrid Angular/AngularJS app.

I've been able to downgrade my angular components using this code in the main.ts file:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { downgradeModule } from '@angular/upgrade/static';
import { AppModule } from '../new-app/src/app/app.module';

const bootstrapFn = (extraProviders: StaticProvider[]) => {
  const platformRef = platformBrowserDynamic(extraProviders);
  return platformRef.bootstrapModule(AppModule);
};

const downgradedModule = downgradeModule(bootstrapFn);

angular.module('old.angular.js.app', [..., downgradedModule])

While everything works fine when the ng build and ng serve commands are used, there is a problem with the prod mode - the compiled js code for AppModule is not generated when I run ng build --prod (I can't see it as part of the compiled main.{hash}.js file).

I suspect this is due to the fact that AppModule is bootstrapped on demand but I've no idea how to work around that and get this module to compile.

At the moment, I'm getting this error in my angularjs app since AppModule hasn't been compiled

Error: [$injector:modulerr] Failed to instantiate module old.angular.js.app due to:
Error: [$injector:modulerr] Failed to instantiate module old.angular.js.app.newmodule due to:
Error: [$injector:nomod] Module 'old.angular.js.app.newmodule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
DaggeJ
  • 2,094
  • 1
  • 10
  • 22
ce57
  • 128
  • 8

1 Answers1

0

I ended up adding a downgraded angular "bootstrapper" component to index.html whose only purpose is to make sure the new angular app gets bootstrapped as soon as possible.

import { Component } from '@angular/core';
// This component is used to bootstrap the angular part of the application through index.html
@Component({
    selector: 'app-bootstrapper',
    template: ''
})
export class BootstrapperComponent { }

Index.html

<body>
    <div ui-view=""></div>
    <downgraded-bootstrapper></downgraded-bootstrapper>
</body>

angular-downgrades.ts;

angular.module('your-app')
    .directive('downgradedBootstrapper', downgradeComponent({ component: BootstrapperComponent }) as angular.IDirectiveFactory)

You may also need to tweak angular.json settings for production. We had to set "optimization": false in order to have our production build working (you can also try to set "aot": false).

Hope any of this helps.

DaggeJ
  • 2,094
  • 1
  • 10
  • 22