Angular 16中addImportToModule返回空数组问题求助
问题排查与解决方案
你的代码里主要有两个问题导致addImportToModule返回空数组:
1. 模块路径使用了绝对路径
Tree的API基于工作区根目录,应该使用相对路径而非绝对路径。你当前用的/src/app/app.module.ts是绝对路径,会导致AST工具无法正确定位NgModule装饰器的位置,从而无法生成修改。
2. 未处理insertImport返回null的情况
当目标导入已经存在时,insertImport会返回null,直接将其加入changes数组会导致后续遍历出错,也可能干扰addImportToModule的逻辑。
另外,还要确保导入了所有必要的类型(比如Change、InsertChange),避免隐性错误。
修正后的代码
import { addImportToModule, insertImport} from '@schematics/angular/utility/ast-utils'; import { InsertChange, Change } from '@schematics/angular/utility/change'; import { Tree, SchematicContext, SchematicsException } from '@angular-devkit/schematics'; import { normalize } from '@angular-devkit/core'; import * as ts from 'typescript'; function addImport( importPath: string, importName: string, tree: Tree, context: SchematicContext ): Tree { // 改用相对路径,去掉开头的斜杠 const modulePath = 'src/app/app.module.ts'; if (!tree.exists(modulePath)) { throw new SchematicsException(`文件 ${modulePath} 不存在!`); } const appModuleFile = tree.read(normalize(modulePath))?.toString('utf-8'); if (appModuleFile === null) { throw new SchematicsException(`无法读取模块文件 ${modulePath}!`); } const source = ts.createSourceFile( modulePath, appModuleFile, ts.ScriptTarget.ES2022, // 指定明确的ScriptTarget,匹配Angular 16的TypeScript版本(5.1) true ); const importChange = insertImport(source, modulePath, importName, importPath, true); const importsChanges = addImportToModule(source, modulePath, importName, importPath); // 处理insertImport返回null的情况,避免加入无效值 const changes: Change[] = []; if (importChange) { changes.push(importChange); } changes.push(...importsChanges); const importRecorder = tree.beginUpdate(modulePath); for (const change of changes) { context.logger.debug(change.description); if (change instanceof InsertChange) { context.logger.info('找到需要插入的修改。'); importRecorder.insertLeft(change.pos, change.toAdd); } else { context.logger.info('检测到非插入类型的修改。'); } } tree.commitUpdate(importRecorder); return tree; }
额外验证点
- 确认调用
addImport时传入的importName和importPath正确,比如要添加CommonModule的话,应该传入importPath: '@angular/common',importName: 'CommonModule'。 - 检查你的AppModule文件格式是否规范,比如NgModule装饰器的大括号、逗号是否正确,AST解析对格式敏感。
内容的提问来源于stack exchange,提问作者Paweł Poręba
相关产品推荐
相关产品推荐

