Angular 15生成组件时如何恢复OnInit生命周期钩子与构造函数?
自定义Angular CLI组件模板,默认包含OnInit与构造函数
方法一:直接修改Angular CLI内置模板(快速生效,但CLI更新后会被覆盖)
定位CLI模板文件路径
- 全局安装的CLI:执行命令
npm root -g获取全局npm包根目录,模板路径为该目录下的@angular/cli/src/lib/schematics/component/files - 项目本地安装的CLI:路径为项目根目录下的
node_modules/@angular/cli/src/lib/schematics/component/files
- 全局安装的CLI:执行命令
修改TypeScript组件模板
找到并编辑__name@dasherize__.component.ts文件,替换内容为:import { Component, OnInit } from '@angular/core'; @Component({ selector: '{{ selector }}', templateUrl: './{{ name }}.component.html', styleUrls: ['./{{ name }}.component.css'] }) export class {{ className }}Component implements OnInit { constructor() { } ngOnInit(): void { } }保存后,后续使用
ng generate component生成的组件就会默认包含构造函数和OnInit钩子。
方法二:创建自定义Schematic(长期稳定,不受CLI更新影响)
初始化自定义Schematic项目
全局安装Schematic工具:npm install -g @angular-devkit/schematics-cli创建空白Schematic项目:
schematics blank --name=custom-component配置自定义组件模板
- 在
src/custom-component目录下创建files文件夹,放入修改后的组件模板文件(参考方法一中的修改后的TS模板,保持变量占位符如{{ className }}不变) - 编辑
schema.json定义模板参数(可参考Angular官方CLI的schema配置) - 编辑
index.ts实现模板生成逻辑,核心代码示例:import { Rule, SchematicContext, Tree, apply, url, template, mergeWith } from '@angular-devkit/schematics'; import { strings } from '@angular-devkit/core'; export function customComponent(options: any): Rule { return (tree: Tree, context: SchematicContext) => { const templateSource = apply(url('./files'), [ template({ ...strings, ...options, }), ]); return mergeWith(templateSource)(tree, context); }; }
- 在
本地测试与使用
在Angular项目中运行自定义Schematic生成组件:schematics ../custom-component:custom-component --name=test-component也可将Schematic发布到npm或通过
npm link本地关联,实现全局调用。
内容的提问来源于stack exchange,提问作者Michele Angelini
相关产品推荐
相关产品推荐

