You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止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的项目配置:

  1. 打开项目根目录的angular.json文件
  2. 定位到projects -> [你的项目名称] -> schematics节点(若不存在则手动创建该节点)
  3. 添加@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:25:56