Havald
Havald

Reputation: 739

Compiler warning when lazy loading component with dynamic import

i am using Angular 9 and its ivy compiler.

I try to lazy load a component with the dynamic import function and the componentFactoryResolver:

const comp = await import('path/component.ts').then(x => x.component)
const factory = this._resolver.resolveComponentFactory(comp);
this.viewContainerRef.createComponent(factory)

It works as expected, i can load the component and use it, but when the lazy loaded component uses a sibling component declared in the same module as the lazy loaded componente i get the following warning:

WARNING in ./src/app/core/components/component.html 1:0 Module parse failed: Unexpected token (1:0)You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

The problem with this warning is, that it apparently creates .js files in the dist folder containing the warning.

Upvotes: 2

Views: 1136

Answers (2)

Havald
Havald

Reputation: 739

Found the problem.

I am using dynamic paths in the import() function to reduce the path length you need to write when adding a new component.

Apparently webpack can not handle such dynamic paths and prints out warnings.

I now created a dictionary of all components with the whole import like this:

componentPath: () => import('./src/core/component/component.ts')

Edit:

tsconfig.json:
  "compilerOptions": {
    "baseUrl": "./src",
    "downlevelIteration": true,
    "paths": {
      "@app/*": ["app/*"],
      "@env/*": ["environments/*"]
    },
}

An example in my environment.ts:

        export const DynamicComponents = {
    
       exampleComp = () => import('./src/core/exampleComp/example-comp.component').(x => x.ExampleComp)
       ...
       
    }

The component file:

@Component(...)
export class ExampleComp {
}


@NgModule({
declarations: [ExampleComp]
}...)

export class ExampleCompModule {
}

Upvotes: 1

Enea Jahollari
Enea Jahollari

Reputation: 306

When you lazy load a component with componentFactoryResolver, that component isn't connected to the module you are declaring it, so it doesn't know what is that other component.

I suggest reading more about it here:

Upvotes: 1

Related Questions