基于Yeoman搭建自己的脚手架-----自定义Generator

创建Generator 模块

Generator 本质上就是一个NPM模块,但是Generator 有一个特定结构

在这里插入图片描述
首先我们创建一个文件夹当做目录

# mkdir generator-sample
# yarn init
# yarn add yeoman-generator
# code .   //打开VScode

然后我们按照按照上面的基础结构创建相应的文件夹
在这里插入图片描述
在index js 中可以直接创建

consst Generator =require('yeoman-generator')

module.exports = class extends Generator{
	writing(){
		//yeoman 自动在生成文件阶段调用此方法
		// 我们这里尝试往项目目录中写入文件
		this.fs.writing(
			this.dedtinationPath('temp.txt'),
			Math.random().toString()
		)
	}
}
//命令行
#  yarn link
# yo sample //文件名


## 根据模板创建文件

```javascript
consst Generator =require('yeoman-generator')

module.exports = class extends Generator{
	writing(){
		//yeoman 自动在生成文件阶段调用此方法
		// 我们这里尝试往项目目录中写入文件
		//this.fs.writing(
		//	this.dedtinationPath('temp.txt'),
		//	Math.random().toString()
		//)
			
			//通过末班方式写入文件到到目标目录
			const tmpl=this.templatePath('foo.txt')
			//输出目标路径
			const output = this.destinationPath('foo.txt')
			//模板数据上下文
			const context={title:'Hello dzj-',sucess:false}
			this.fs.copyTpl(tmpl,output,context )
	}
}

相对于手动去创建每一个文件,模块的方式大大提高了效率

接受用户输入------prompting()

consst Generator =require('yeoman-generator')

module.exports = class extends Generator{
	paompting(){
		// yeoman 在询问用户环节会自动调用此方法
		// 在此方法中可以调用父类的 prompt() 方法 发出对用户的命令行询问
		return this.prompt([
			{
				type:'input',
				name:'name',
				message:'your Project name',
				default:this.appname ,//appname  为项目中生成目录名称
			}
		])
		。then(answers=>{
		//	answers =>{ name :'  user input name'}
			this.answers=answers
		})
	}
	writing(){
		//yeoman 自动在生成文件阶段调用此方法
		// 我们这里尝试往项目目录中写入文件
		//this.fs.writing(
		//	this.dedtinationPath('temp.txt'),
		//	Math.random().toString()
		//)
			
			//通过末班方式写入文件到到目标目录
			const tmpl=this.templatePath('foo.html')
			//输出目标路径
			const output = this.destinationPath('bar.html')
			//模板数据上下文
			const context=this.answers
			this.fs.copyTpl(tmpl,output,context )
	}
}
yo sample //名称

以上内容均为个人学习笔记,不存在任何其他或者商业行为 ,如有侵权或者其他,必删除。请私聊或者评论告知。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值