jvandemo / generator-angular2-library

Yeoman generator to create an Angular library
MIT License
752 stars 122 forks source link

Error encountered resolving symbol values statically... #163

Closed Davy-F closed 7 years ago

Davy-F commented 7 years ago

This one is racking my brains. I've searched and been through every solution on Google and GitHub, but to no avail.

Getting the following error when trying to run a new project which is consuming my library:

Error encountered resolving symbol values statically. Calling function 'Co mmonModule', function calls are not supported. Consider replacing the function o r lambda with a reference to an exported function, resolving symbol AppModule in C:/Development/AppTemplate/Application/WebClient/src/app.module.ts, resolving s ymbol AppModule in C:/Development/AppTemplate/Application/WebClient/src/app.modu le.ts

I believe my library is statically-analyzable for aot, and I also ran ngc --aot=false just to make sure, but I still get the error.

Here's my library CommonLibraryModule - index.ts:

//Angular Components
import {NgModule, ModuleWithProviders, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, ErrorHandler}      from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {CommonModule} from "@angular/common";
import {HttpModule} from '@angular/http';
import {RouterModule } from '@angular/router';

//Common
import {NavComponent, PrioritySortPipe} from './components/site-components/nav/nav.component';
import {AppNameComponent} from './components/site-components/app-name/app-name.component';
import {ToastContainer} from './components/site-components/toast-container/toast.container';
import {ToastComponent} from './components/site-components/toast/toast.component';
import {NumberSpinnerComponent} from './components/site-components/number-spinner/number-spinner.component';
import {TableComponent} from './components/table/table.component';
import {TableComponentRowProcessor} from './components/table/table.component.processor';
import {TabbableComponent} from './components/site-components/tabbable/tabbable.component';
import {TabComponent} from './components/site-components/tab/tab.component';
import {DatePicker} from './components/site-components/datepicker/datepicker.component';
import {AutocompleteDirective} from './directives/autocomplete/autocomplete.directive';
import {CollapsibleComponent} from './components/site-components/collapsible/collapsible.component';
import {ChartComponent} from './components/chart/chart.component';
import {KnobComponent} from './components/knob/knob.component';
import {PaginatedTableComponent} from './components/data-components/paginated-table/paginated-table.component';
import {PopupComponent} from './components/site-components/popup/popup.component';
import {LoadingComponent} from './components/site-components/loading/loading.component';
import {SearchComponent} from './components/site-components/search/search.component';
import {TimelineContainerComponent} from './components/site-components/timeline-container/timeline-container.component';
import {PaginatorComponent} from './components/site-components/paginator/paginator.component';
import {SubtitleComponent} from './components/site-components/subtitle/subtitle.component';
import {PercentDiffComponent} from './components/helper-components/pct-diff.component';
import {LegendComponent} from './components/helper-components/legend.component';
import {UserMessageComponent} from './components/site-components/user-message/user-message.component';
import {AutocompleteList} from "./components/site-components/autocomplete-list/autocomplete-list.component";
import {DropDownComponent} from './components/site-components/dropdown/dropdown.component';
import {FilterPanelComponent} from './components/site-components/filter-panel/filter-panel.component';
import {UserComponent} from './components/site-components/user/user.component';
import {HourglassComponent} from './components/site-components/loading/hourglass/hourglass.component';
import {ButtonComponent} from './components/site-components/button/button.component';
import {DropDownItemComponent} from './components/site-components/dropdown-item/dropdown-item.component';
import {DrilldownComponent} from './components/data-components/drilldown/drilldown.component';
import {CurrentYearComponent} from './components/helper-components/current-year.component';
import {KeysPipe} from './pipes/keys.pipe';
import {CaseSplitPipe} from './pipes/case-split.pipe';
import {NumberPipe} from './pipes/number.pipe';
import {RelevantOpsPipe} from './pipes/relevantops.pipe';
import {TimeDiffPipe} from './pipes/time-diff.pipe';
import {OrderByPipe} from './pipes/orderby.pipe';
import {EllipsisPipe} from './pipes/ellipsis.pipe';

//Common Services
import {DashboardService} from './services/dashboard.service';
import {AccountService} from './services/account.service';
import {AnimatorService} from './services/animator.service';
import {CollapsibleManagementService} from './services/collapsible-mgmt.service';
import {ColourService} from './services/colour.service';
import {CredentialManagementService} from './services/credential-management.service';
import {IdService} from './services/id.service';
import {LoggingService} from './services/logging.service';
import {ParamSerialisationService} from './services/param-serialisation.service';
import {RouteService} from './services/route.service';
import {SlugService} from './services/slug.service';
import {ErrorService} from './services/data/error.service';
import {FilterService} from './services/data/filter.service';
import {HttpWrapperService} from './services/data/httpWrapperService';
import {ContextMenuService} from './services/ui/context-menu.service';
import {PagingService} from './services/ui/paging.service';
import {StateService} from './services/ui/state.service';
import {ToastService} from './services/ui/toast.service';

//Common Other
import {canActivateRoute} from './exports/can-activate-route.function';
import {DashboardModelFactory} from './factories/dashboard-model.factory';
import {DashboardRowModelFactory} from './factories/dashboard-row-model.factory';
import {DrilldownFactory} from './factories/drilldown.factory';
import {KnobFactory} from './factories/knob.factory';
import {TableFactory} from './factories/table.factory';

//Export All
export *  from './components/site-components/nav/nav.component';
export *  from './components/site-components/app-name/app-name.component';
export *  from './components/site-components/toast-container/toast.container';
export *  from './components/site-components/toast/toast.component';
export *  from './components/site-components/number-spinner/number-spinner.component';
export *  from './components/table/table.component';
export *  from './components/table/table.component.processor';
export *  from './components/site-components/tabbable/tabbable.component';
export *  from './components/site-components/tab/tab.component';
export *  from './components/site-components/datepicker/datepicker.component';
export *  from './directives/autocomplete/autocomplete.directive';
export *  from './components/site-components/collapsible/collapsible.component';
export *  from './components/chart/chart.component';
export *  from './components/knob/knob.component';
export *  from './components/data-components/paginated-table/paginated-table.component';
export *  from './components/site-components/popup/popup.component';
export *  from './components/site-components/loading/loading.component';
export *  from './components/site-components/search/search.component';
export *  from './components/site-components/timeline-container/timeline-container.component';
export *  from './components/site-components/paginator/paginator.component';
export *  from './components/site-components/subtitle/subtitle.component';
export *  from './components/helper-components/pct-diff.component';
export *  from './components/helper-components/legend.component';
export *  from './components/site-components/user-message/user-message.component';
export *  from "./components/site-components/autocomplete-list/autocomplete-list.component";
export *  from './components/site-components/dropdown/dropdown.component';
export *  from './components/site-components/filter-panel/filter-panel.component';
export *  from './components/site-components/user/user.component';
export *  from './components/site-components/loading/hourglass/hourglass.component';
export *  from './components/site-components/button/button.component';
export *  from './components/site-components/dropdown-item/dropdown-item.component';
export *  from './components/data-components/drilldown/drilldown.component';
export *  from './components/helper-components/current-year.component';
export *  from './pipes/keys.pipe';
export *  from './pipes/case-split.pipe';
export *  from './pipes/number.pipe';
export *  from './pipes/relevantops.pipe';
export *  from './pipes/time-diff.pipe';
export *  from './pipes/orderby.pipe';
export *  from './pipes/ellipsis.pipe';
export * from './services/dashboard.service';
export * from './services/account.service';
export * from './services/animator.service';
export * from './services/collapsible-mgmt.service';
export * from './services/colour.service';
export * from './services/credential-management.service';
export * from './services/id.service';
export * from './services/logging.service';
export * from './services/param-serialisation.service';
export * from './services/route.service';
export * from './services/slug.service';
export * from './services/data/error.service';
export * from './services/data/filter.service';
export * from './services/data/httpWrapperService';
export * from './services/ui/context-menu.service';
export * from './services/ui/paging.service';
export * from './services/ui/state.service';
export * from './services/ui/toast.service';
export * from './exports/can-activate-route.function';
export * from './factories/dashboard-model.factory';
export * from './factories/dashboard-row-model.factory';
export * from './factories/drilldown.factory';
export * from './factories/knob.factory';
export * from './factories/table.factory';

@NgModule({
  imports: [ 
      BrowserModule, CommonModule, HttpModule, RouterModule, FormsModule, ReactiveFormsModule
   ],
   declarations: [ NavComponent, AppNameComponent, ToastContainer, NumberSpinnerComponent, 
      TableComponent, TableComponentRowProcessor, TabbableComponent, TabComponent, DatePicker, AutocompleteDirective, CollapsibleComponent, 
      ChartComponent, KnobComponent, PaginatedTableComponent, PopupComponent, LoadingComponent, 
      SearchComponent, TimelineContainerComponent, PaginatorComponent, SubtitleComponent, 
      ToastComponent, PercentDiffComponent, LegendComponent, UserMessageComponent, DropDownComponent, AutocompleteList, 
      FilterPanelComponent, UserComponent, HourglassComponent, ButtonComponent, DropDownItemComponent,
      DrilldownComponent, CurrentYearComponent,  
      KeysPipe, CaseSplitPipe, NumberPipe, RelevantOpsPipe, TimeDiffPipe, PrioritySortPipe, 
      OrderByPipe, EllipsisPipe, canActivateRoute,
      DashboardModelFactory, DashboardRowModelFactory, DrilldownFactory, KnobFactory, TableFactory
    ],   
  exports: [ 
      NavComponent, AppNameComponent, ToastContainer, NumberSpinnerComponent, 
      TableComponent, TableComponentRowProcessor, TabbableComponent, TabComponent, DatePicker, AutocompleteDirective, CollapsibleComponent, 
      ChartComponent, KnobComponent, PaginatedTableComponent, PopupComponent, LoadingComponent, 
      SearchComponent, TimelineContainerComponent, PaginatorComponent, SubtitleComponent, 
      ToastComponent, PercentDiffComponent, LegendComponent, UserMessageComponent, DropDownComponent, AutocompleteList, 
      FilterPanelComponent, UserComponent, HourglassComponent, ButtonComponent, DropDownItemComponent,
      DrilldownComponent, CurrentYearComponent,  
      KeysPipe, CaseSplitPipe, NumberPipe, RelevantOpsPipe, TimeDiffPipe, PrioritySortPipe, 
      OrderByPipe, EllipsisPipe, canActivateRoute,
      DashboardModelFactory, DashboardRowModelFactory, DrilldownFactory, KnobFactory, TableFactory
    ]              
})
export class CommonLibraryModule {
    static forRoot():ModuleWithProviders {
        return {
            ngModule: CommonLibraryModule,
            providers: [
                DashboardService,
                AccountService,
                AnimatorService,
                CollapsibleManagementService,
                ColourService,
                CredentialManagementService,
                IdService,
                LoggingService,
                ParamSerialisationService,
                RouteService,
                SlugService,
                ErrorService,
                FilterService,
                HttpWrapperService,
                ContextMenuService,
                PagingService,
                StateService,
                ToastService
            ]
        };
    }
}

And here's my AppModule:

//Angular Components
import {NgModule, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, ErrorHandler}      from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {routing, appRoutingProviders} from './route.config';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {RouterModule } from '@angular/router';
import {CommonModule} from "@angular/common";

//Page Components
import {AppComponent} from './components/app/app.component';
import {DashboardComponent} from './components/page-components/dashboard/dashboard.component';
import {LoginComponent} from './components/page-components/login/login.component';
import {ErrorComponent} from './components/page-components/error/error.component';
import {AdminComponent} from './components/page-components/admin/admin.component';
import {UserProfileComponent} from './components/page-components/user-profile/user-profile.component';

//Common Library
import {CommonLibraryModule} from 'commonlibrary';

@NgModule({
  imports: [ 
    // module dependencies
    BrowserModule, CommonModule, 
    RouterModule.forRoot(routing, { useHash: Boolean(history.pushState) === false }), 
    FormsModule, ReactiveFormsModule, HttpModule, CommonLibraryModule.forRoot()
  ],       
  declarations: [ 
    // components and directives
    AppComponent, DashboardComponent, LoginComponent, ErrorComponent, AdminComponent, UserProfileComponent
  ],   
  bootstrap: [ AppComponent ],     // root component
  providers: [ appRoutingProviders ]                   // services
})
export class AppModule { }

I'm hoping I've missed something really obvious. I feel like I'm so close but falling at the last hurdle.

With the error stating "Calling function 'CommonModule'", does this mean that the error is within the CommonModule index.ts? Or could it be a probably within one of the components declared?

I know this is more of a problem with my code than the library generator, but any help would be massively appreciated.

Davy-F commented 7 years ago

After some digging, if I remove the index.d.ts file the error gets replaced with a new one.

Error: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 5342:25 in the original .ts file), resolving symbol DashboardService in C:/Development/AppTemplate/Application/WebClient/node_module s/commonlibrary/index.js, resolving symbol DashboardComponent in C:/Development/A ppTemplate/Application/WebClient/src/components/page-components/dashboard/dashbo ard.component.ts, resolving symbol DashboardComponent in C:/Development/AppTempl ate/Application/WebClient/src/components/page-components/dashboard/dashboard.com ponent.ts

So at least I can now possibly pinpoint where the code might be falling over within the CommonLibrary, perhaps due to not being compatible with AOT??

This is the line in question:

5342: var DashboardService = (function () {

...changing it to...

var DashboardService = (export function () {

...fixes the issue and then moves on to the next error.

Update

After going through and fixing these, nope. Back to the original error. Hmm...

jvandemo commented 7 years ago

@Davy-F — Have you set up the path mapping as outlined in step 12 of https://github.com/jvandemo/generator-angular2-library#consuming-your-library-during-development?

Thanks!

Davy-F commented 7 years ago

Hi @jvandemo. Yes , I have. Here's my tsconfig file:

{
  "compilerOptions": {
    "baseUrl": "",
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es2015", "dom"],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "./node_modules/@types/"
    ],
    "paths": { 
      "@angular/*": ["./node_modules/@angular/*"],
      "rxjs/*": ["./node_modules/rxjs/*"]
    }
  },

"files": [
    "src/app.module.ts",
    "src/main.ts"
  ],

  "angularCompilerOptions": {
   "genDir": "aot",
   "skipMetadataEmit" : true
 }
}
broweratcognitecdotcom commented 7 years ago

I mentioned this in another similar issue. And it might not help but here goes anyway: Ensure that the name attribute at the top of package.json and ./src/package.json and the flatModuleId in ./src/tsconfig.es5.json are the same. I had the same error and it was because I renamed something and forgot to check these places.

Davy-F commented 7 years ago

@broweratcognitecdotcom Thank you for your reply. Unfortunately doesn't help out my issue as the name attribute is the same, but might always help out someone else out in the future.

broweratcognitecdotcom commented 7 years ago

That you add your components to your imports: [] for your module seems strange to me. I'm not saying it is incorrect. I am just wondering why you do that since adding them to declarations and optionally to exports should be enough. I don't do this. I don't know what effect it has, but in my case, I don't have this error. My module does not contain nearly as many parts as yours.

Davy-F commented 7 years ago

@broweratcognitecdotcom They've only been added to Declarations and Exports in the library module, which I believe is standard practice? I've updated my original code to make this clearer. Thanks for your help.

broweratcognitecdotcom commented 7 years ago

"only been added to Declarations and Exports" ... yes, I believe that is standard practice, although I see people adding components to imports sometimes and always wonder why. Thanks for updating. Try commenting out everything you're importing in index.ts. Build the lib, then build the app. See if it works. then start uncommenting stuff a bit at a time and repeat...

tytskyi commented 7 years ago

@Davy-F i am facing the same issue and i think it's because of order of import/export * statements. I already faced similar issue and it was relatively easy to reorder things. But since then library is large and hard to try this approach.

I am using different approach for testing (consuming) library than npm link. It is not ideal, but works. Try if it works for you.

  1. Make sure to unlink your library from npm.
  2. Install you library directly from file system from dist folder (https://stackoverflow.com/a/8089029). Just don't commit that change to your git.
  3. Try if error goes away.

Theoretically this installs the same code of library if it would be installed from npm registry.

robertbrower-technologies commented 7 years ago

I bet if you switch from using npm link to using an in-house npm repo, your problem would be solved. Is this possible? One other thing I forgot to mention is that I set all of the versions of everything to the same version in all of my package.json files, including my libraries and apps, and don't use ~ or ^. If I add any dependency outside of what the generator gives me, I add it to both dependencies, and peerDependencies in package.json and ./src/package.json of my library. Maybe this is overkill, but I can build --aot and --prod and it's all working very nicely w/ version 9.0.0 of the generator.

Davy-F commented 7 years ago

@tytskyi @robertbrower-technologies Unfortunately I'm not using npm link and using VSTS as a private repository. I have been testing the library by copying and pasting the dist folder and still been getting the errors unfortunately.

I will go through the dependencies in the package.json files and update their ~/^, but I believe all versions are the same. Perhaps one or two could be missing from peerDependencies.

I'll also experiment with the import/export statements ordering.

Davy-F commented 7 years ago

I've somehow fixed this error. I wish I had more information on how exactly I fixed it , but I don't. I was going through my application and library, trying to amend all AOT compatibility fixes I could find. I also removed all console.logs in my library, because apparently this isn't supported.

I also amended all tsconfig files so they had pathsincluded.

"paths": { 
    "@angular/*": ["../node_modules/@angular/*"],
    "rxjs/*": ["../node_modules/rxjs/*"]
},

It might've been that there was an incorrect value or issue with my tsconfig, but I'm not 100%. The error just disappeared.

After the error cleared down, the console highlighted many 'AOT' incompatibility errors from within my library. Which is reassuring because I didn't want to fix these blindly and also means that AOT compatibility errors are not linked with this particular error as such.

However... :stuck_out_tongue:

I am now getting this error in the console :

Uncaught ReferenceError: commonlibrary is not defined at main.js:4

I amended my rollup external globals, as well as adding "egresscommon/*": ["./node_modules/egresscommon/*"] to my tsconfig paths, but unfortunately the issue persists.

Any ideas team? I can always create a new issue if you feel this one should now be closed?

broweratcognitecdotcom commented 7 years ago

What is on line 4 of main.js? ***Note... I am not using "paths": {... in tsconfig or anywhere else because I am using an internal npm repository. I don't know, but maybe this helps you: https://www.npmjs.com/package/sinopia

Davy-F commented 7 years ago

@broweratcognitecdotcom I will have a look into Sinopia, however I think we will stick with the current VSTS setup to keep everything in one place.

Here's main.js. It's actually pointing to the app.module.ngfactory: image

I believe it's falling over on this line of the app,module.ngfactory: import * as i14 from 'commonlibrary';

Which is created from the following line in my app.module: import {CommonLibraryModule} from 'commonlibrary';

In the App's Package.json, do you declare your library module as devDependency / peerDependency?

broweratcognitecdotcom commented 7 years ago

Just in "dependencies": [] in my app's package.json. i am convinced that your lib and your app are being built using different physical @angular/core files.

In your lib's package.json AND .src/package.json make sure you have these at a minimum in your peerDeps:

"peerDependencies": { "@angular/core": "4.1.3", "rxjs": "5.1.0", "zone.js": "0.8.4", }

Your app and lib ~must~ import the same physical files from @angular/core, where NgModule is defined. I know this stuff is tricky and will cause you to lose 2 weeks and some hair, but once you get it working, you'll be golden.

broweratcognitecdotcom commented 7 years ago

my main.ts just in case it helps:

import { enableProdMode, LOCALE_ID } from '@ angular/core'; import { platformBrowserDynamic } from '@ angular/platform-browser-dynamic';

import { AppModule } from './app/app.module'; import { environment } from './environments/environment';

if (environment.production) { enableProdMode(); }

let userLang = window.navigator.language.split('-')[0]; userLang = /(de|en)/gi.test(userLang) ? userLang : 'en';
platformBrowserDynamic([{provide: LOCALE_ID, useValue: userLang}]).bootstrapModule(AppModule, {providers: [{provide: LOCALE_ID, useValue: userLang}]});

broweratcognitecdotcom commented 7 years ago

You're using a module factory. I don't know anything about that. Can you explain why? you can find me here: https://gitter.im/angular/angular. I'll give you some realtime help if you need it.

Davy-F commented 7 years ago

@broweratcognitecdotcom I'm running the app in AOT mode (or trying to). Maybe this does make a difference to how the library is consumed, I'm not sure. Here's a bit more info on bootstrapping with AOT compilation: https://angular.io/guide/aot-compiler#bootstrap

My end goal is to build the application with a library and be able to run it in both AOT/JIT mode.

Davy-F commented 7 years ago

Compiling in JIT mode I get the following: GET http://localhost:3000/node_modules/commonlibrary/ 404 (Not Found)

which confirms it is definitely broken...

broweratcognitecdotcom commented 7 years ago

Can you show me your app module factory? btw, I am in here: https://gitter.im/angular/angular

Davy-F commented 7 years ago

I've resolved my issues by updating to angular-cli which seems to be working a lot better than the standalone Angular 4.0.0 build I had before.

jvandemo commented 7 years ago

@Davy-F — Thank you for the update! 👍