如何阻止Angular 17 CLI生成组件时自动导入CommonModule
如何让Angular 17 CLI生成独立组件时默认不带CommonModule
方法一:生成组件时使用命令行参数
直接在生成命令后添加--skip-imports参数,即可让生成的组件imports数组为空:
ng g c new-component --skip-imports
执行后生成的组件代码示例:
@Component({ selector: 'app-new-component', standalone: true, imports: [], templateUrl: './new-component.component.html', styleUrl: './new-component.component.scss', changeDetection: ChangeDetectionStrategy.OnPush }) export class NewComponentComponent {}
方法二:修改项目全局配置(永久生效)
如果希望每次生成组件都默认跳过CommonModule的自动导入,可以修改angular.json的项目配置:
- 打开项目根目录的
angular.json文件 - 定位到
projects -> [你的项目名称] -> schematics节点(若不存在则手动创建该节点) - 添加
@schematics/angular:component的配置项,设置skipImports为true:
{ "projects": { "your-project-name": { // 其他项目配置... "schematics": { "@schematics/angular:component": { "standalone": true, // 若项目默认生成独立组件可保留,否则可移除 "skipImports": true } } } } }
保存配置后,后续执行ng g c new-component时,生成的组件会自动不带CommonModule的导入。
内容的提问来源于stack exchange,提问作者Siwyus
相关产品推荐
相关产品推荐

