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

使用ts-morph向NgModule的declarations配置中添加组件的实现问题

正确实现代码

import { SyntaxKind, ClassDeclaration, ObjectLiteralExpression, ArrayLiteralExpression } from "ts-morph";

// 1. 定位目标NgModule类
const classDeclaration = sourceFile
  .getClasses()
  .find(c => c.getName() === "ExampleModule") as ClassDeclaration;

// 2. 读取NgModule装饰器的配置对象
const ngModuleDecorator = classDeclaration.getDecorator("NgModule")!;
const moduleConfig = ngModuleDecorator.getArguments()[0] as ObjectLiteralExpression;

// 3. 读取/初始化declarations配置项
let declarationsProp = moduleConfig.getProperty("declarations");
if (!declarationsProp) {
  // 兼容不存在declarations的场景,自动新增
  declarationsProp = moduleConfig.addProperty({
    name: "declarations",
    initializer: "[]"
  });
}
const declarationsArray = declarationsProp.getInitializer() as ArrayLiteralExpression;

// 4. 插入组件标识符(不需要加引号)
declarationsArray.addElements(["ExampleComponent"]);

// 5. 自动添加组件的import声明(替换为实际组件路径)
sourceFile.addImportDeclaration({
  moduleSpecifier: "./example.component",
  namedImports: ["ExampleComponent"]
});

// 持久化修改到文件
sourceFile.save();

原方案问题说明

  • 手动插入文本的方案存在两个问题:一是插入了带双引号的字符串,而组件是无引号的标识符;二是空数组场景下直接在]前加逗号会生成非法语法[, "something new!"]。
  • 读取getStructure()的方案只读取了装饰器的快照数据,没有调用setStructure()回写修改,因此不会生效。

内容的提问来源于stack exchange,提问作者lili-code

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:12:01