Creating new module using Angular schematics

1k views Asked by At

We would like to use schematics to generate a feature module that contains components we are generating over and over.

I've started following this tutorial: https://medium.com/@michael.warneke/merging-custom-angular-schematics-c14a303f63b6

But when I created the __name@dasherize@singularize__.module.ts file and try to build the project I get TS compilation errors.

This is how my file looks like:

import { ModuleWithProviders, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
    imports: [
        CommonModule,
    ],
    declarations: [],
    providers: [],
    entryComponents: []
 })
export class <%= classify(name) %>Module {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: <%= classify(name) %>Module,
            providers: []
        };
     }
}

And this is the error:

error TS6133: 'ModuleWithProviders' is declared but its value is never read.

1

There are 1 answers

0
ericksoen On

From your post, it sounds like this is a compile-time error, i.e., npm run build rather than a generation-time error, i.e., ng new CustomSchematic --collection my-custom-schematic.

The most frequent culprit I have seen for this behavior is that Typescript is running its validation rules against your schematic assets. In this case, I would expect your tsconfig.json to have the following property and value, "noUnusedLocals": true. Setting that property to false is probably not a good long time strategy, since it would mean all of your schematic application code no longer executes that validation rule either.

Instead (and what I've chosen to do on my projects), is to add the following property to the tsconfig.json file:

"exclude": [
    "src/*/files/**/*"
]

This will properly exclude all of your assets underneath your files folder of every schematic in your schematic collection.

/src
  /ng-new
     /files
        custom-asset.ts
        custom-asset.html
     index.ts
     index_spec.ts
  /custom-service
     /files
        custom-asset.ts
     index.ts
     index_spec.ts

I wasn't able to entirely replicate your issue so if you have a public repo link, can you can share it. However, when I remove excludes setting in my tsconfig.json I go from compilation to a significant number of Typescript errors, so I have some confidence that this is the right direction.

As one final hint, if you are using VS code and have the Problems panel displayed, you can apply the same error suppression strategy using the !src/*/files/**/* file path.

Suppress TS errors in schematic assets in VS Code