Angular CLI自定义ng generate组件文件结构配置问询
方案一:自定义Angular Schematics(推荐)
这是Angular官方支持的自定义代码生成方式,能完全替代默认的ng generate component命令,生成你想要的结构,还能复用配置到多个项目。
步骤如下:
- 全局安装Schematics CLI:
npm install -g @angular-devkit/schematics-cli - 创建一个新的Schematics项目:
schematics blank --name=custom-component - 在项目的
files目录下,按照你的期望结构创建模板文件:ts/__name@dasherize__.component.ts:组件类模板ts/__name@dasherize__.component.spec.ts:组件测试模板tpl/__name@dasherize__.component.html:组件模板scss/__name@dasherize__.component.scss:组件样式
- 修改
schema.json文件,添加必要的配置项(比如组件名参数),并在index.ts中调整文件生成的路径映射,将根路径指向src/app/components/{{name}}/,对应到各个子文件夹。 - 把你的Schematics发布到npm仓库,或者通过
npm link本地链接到你的Angular项目。 - 在Angular项目中使用自定义命令生成组件:
ng generate custom-component:custom-component pippo
这种方式能完全自动化生成符合要求的组件结构,无需手动调整文件位置。
方案二:使用BAT脚本(快速实现)
如果你不想折腾Schematics,也可以用你提供的BAT脚本来快速生成文件夹结构和空文件,之后手动填充组件代码或者结合ng generate component生成后移动文件。
以下是整理后的BAT脚本:
@echo off setlocal enabledelayedexpansion ECHO ################################# ECHO ################################# ECHO NG COMPONENT CREATOR BY TONY SAMPERI ECHO ################################# ECHO ################################# set folderStatus=N set folderName=newComponent set sourcePath=%cd%\src\app\components cd %sourcePath% echo sourcePath is %sourcePath% call :getFolderName IF "!folderStatus!" == "C" call :createStructure IF "!folderStatus!" == "N" call :failedWarning PAUSE endlocal EXIT /B :getFolderName echo Component name? set /P folderName= IF exist %folderName% ( echo Directory %folderName% already exists! goto :getFolderName ) ELSE ( mkdir %folderName% set folderStatus=C ) EXIT /B :createStructure cd %folderName% echo Moved to %sourcePath%\%folderName% mkdir ts cd ts type NUL > %folderName%.component.ts cd .. mkdir scss cd scss type NUL > %folderName%.component.scss cd .. mkdir tpl cd tpl type NUL > %folderName%.component.html cd .. echo DONE.
脚本功能说明:
- 执行后会提示你输入组件名称,自动检查该组件文件夹是否已存在
- 如果不存在,会在
src/app/components下创建对应组件文件夹,并生成ts、scss、tpl三个子文件夹,以及对应的空组件文件 - 你可以之后手动在这些空文件中添加Angular组件的基础代码,或者先用
ng generate component生成默认结构,再把文件移动到脚本创建的对应文件夹中。
内容的提问来源于stack exchange,提问作者Sampgun
相关产品推荐
相关产品推荐

