plop
yeoman适合在创建项目的时候使用,而plop则适合在项目中使用。比如说,在创建某一个文件的时候总是有html css js 三个文件夹。那么如果我们每次新开一个页面都要创建这三个文件,而文件中也有很多基础代码是和其他文件一样的,那么这时候我们就可以通过polp来自动生成。这里我以自动生成vue文件的基础代码为例。
首先将在项目中安装plop
npm install plop --save-dev
之后在项目根目录中,创建plopfile.js文件,写入以下代码
//polp的入口文件,导出一个函数
module.exports = polp =>{
polp.setGenerator('component',{//component表示的是命令名字
description:'create a new vue component', //提示
prompts:[{ //对象中表示的是交互逻辑
type:'input',
name:'name',
meaasge:'input your vue component name',
default:'myComponent'
}],
actions:[{ //这里创建的是根据上面输入的名字创建vue模板
type:'add', //add表示创建新文件
path:'src/components/{{name}}/{{name}}.vue', //文件路径
templateFile:'plop-templates/component.hbs' //文件模板
}]
})
}
之后我们创建一个plop-temmplates文件夹,在文件夹里面创建component.hbs文件,并写入vue的基本代码
//这里是{{name}}组件
<div>
</div>
<template>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
保存之后,在命令行执行
yarn plop component //这里的component就是setGenerator后面的第一个参数,这里使用yarn不使用npm是因为,yarn会自动找到node_module目录下面的bin里面的可执行程序
至此,一个简易的自动生成vue基本代码的脚手架就做好了