angular 7 cli generate each service, pipe,etc in their own directory

荒凉一梦 提交于 2020-01-16 17:34:26

问题


With early versions of the Angular Cli when I run ng g service services/MyService it created:

services/my-service/my-service.service.ts
services/my-service/my-service.service.spec.ts

But now it creates

services/my-service.service.ts
services/my-service.service.spec.ts

Is there a way to go back to the other behavior without write a verbose ng g service services/my-service/MyService ?I had not found anything related but maybe I am not using the correct keywords.


回答1:


While you can pass --flat=false each time you execute ng generate so that a directory is created based on the service/pipe/directive name, you can actually override default schematics options such as flat at the project level in angular.json to avoid needing to pass the --flat=false option every time on the command line. For example, to set flat to false when executing ng g service services/MyService, you would add an additional property, @schematics/angular:service, in the schematics property of the respective project in angular.json:

...
"projects": {
    "sample-angular": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:service": {
          "flat": false
        }
     },
     ...
}

After adding this override, running the command ng g service services/MyService, generates the following output:

CREATE src/app/services/my-service/my-service.service.spec.ts (349 bytes)
CREATE src/app/services/my-service/my-service.service.ts (138 bytes)

You can override any specific schematics you need whether that is for Pipes, Services, Components, Modules, or Directives. You can see the default schematics options at /node_modules/@angular/cli/lib/config/schema.json. There are a number of options and you can fine tune exactly what you want generated and how to avoid needing to remember and pass options to the command line.

If you have multiple projects, you can create a property schematics at the same level as projects to override schematic options for all projects.

Hopefully that helps!




回答2:


The flat flag defaults to true when generating a service.

I suggest one of the following (haven't tested on Angular CLI 7 but both work with Angular CLI 6)

ng g service services/my-service --no-flat
ng g service services/my-service --flat=false


来源:https://stackoverflow.com/questions/54467807/angular-7-cli-generate-each-service-pipe-etc-in-their-own-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!