Angular DevKit Schematics中如何导航至新项目目录,一键创建应用与库?
问题
我希望基于Schematics打造一款CLI工具,优化工作中的项目创建流程,实现通过一条命令同时生成Angular应用与Angular库。我尝试使用externalSchematic命令,创建应用的操作可正常执行,但调用另一个externalSchematic创建库时,出现了找不到angular.json文件的错误。请问是否有方法实现类似cd命令的目录导航,切换至刚创建的项目目录?
我的代码如下:
export const ngLibrary = (options: Schema): Rule => chain([ externalSchematic('@schematics/angular', 'ng-new', options), externalSchematic('@schematics/angular', 'library', options) ]);
报错信息:
An error occured: Error: Path "/angular.json" does not exist. at HostTree.readText()
解决方案
问题核心是执行library schematic时,当前工作目录仍处于根目录,而ng-new生成的angular.json在新建的项目文件夹内。你可以通过两种方式实现类似cd的目录切换效果:
方法一:使用chdir工具切换全局工作目录
导入Schematics提供的chdir函数,在创建应用后切换到项目目录,再执行库创建命令:
import { chain, externalSchematic, chdir } from '@angular-devkit/schematics'; export const ngLibrary = (options: Schema): Rule => { const projectDir = options.name; // ng-new默认以name作为项目文件夹名 return chain([ externalSchematic('@schematics/angular', 'ng-new', options), chdir(projectDir), // 切换到刚创建的项目目录 externalSchematic('@schematics/angular', 'library', options) ]); };
方法二:给library命令指定工作路径
如果不想修改全局工作目录,可复制原options并添加path属性,指向新建的项目文件夹:
export const ngLibrary = (options: Schema): Rule => { const projectDir = options.name; const libraryOptions = { ...options, path: projectDir }; // 指定库的生成路径为项目目录 return chain([ externalSchematic('@schematics/angular', 'ng-new', options), externalSchematic('@schematics/angular', 'library', libraryOptions) ]); };
注意事项
- 如果你的
ng-new命令使用了自定义directory参数,需把projectDir替换为对应的目录名; chdir会改变后续所有操作的工作目录,适合需要在项目目录下执行多个后续命令的场景;手动指定path仅影响当前library命令,更灵活。
内容的提问来源于stack exchange,提问作者Gillian Perard
相关产品推荐
相关产品推荐

