目录
plopjs
plopjs 是基于Inquirer.js实现的
- 项目根目录添加plopfile.js
module.exports = function (plop) {
// create your generators here
plop.setGenerator('basics', {
description: 'this is a skeleton plopfile',
prompts: [], // array of inquirer prompts
actions: [] // array of actions
});
};
- 优化代码结构
将模板文件相关的单独提取到一个目录plop-template
Eg. 要生成一个组件模板
plop-template/utils.js
exports.notEmpty = name => v =>
!v || v.trim() === '' ? `${
name} is required` : true
plop-template/component/prompt.js
const {
notEmpty } = require('../utils.js')
module.exports = {
description: 'generate vue component',
prompts: [{
type: 'input',
name: 'name',
message: 'component name please',
validate: notEmpty('name')
},
{
type: 'checkbox',
name: 'blocks',
message: 'Blocks:',
choices: [{
name: '<template>',
value: 'template',
checked: true
},
{
name: '<script>',
value: 'script',
checked: true
},
{
name: 'style',
value: 'style',
checked: true
}
],
validate(value) {
if (value.indexOf('script') === -1 && value.indexOf('template') === -1) {
return 'Components require at least a <script> or <template> tag.'
}
return true
}
}
],
actions: data => {
const name = '{
{properCase name}}'
const actions = [{
type: 'add',
path: `src/components/${
name}/index.vue`,
templateFile: 'plop-templates/component/index.hbs',
data: {
name: name,
template: data.blocks.includes('template'),
script: data.blocks.includes('script'),
style: data.blocks.includes('style')
}
}]
return actions
}
}
plop-template/component/index.hbs
{
{#if template}}
<template>
<div />
</template>
{
{/if}}
{
{#if script}}
<script>
export default {
name: '{
{ properCase name }}',
props: {
},
data() {
return {
}
},
created() {
},
mounted() {
},
methods: {
}
}
</script>
{
{/if}}
{
{#if style}}
<style lang="scss" scoped>
</style>
{
{/if}}
plopfile.js
const componentGenerator = require('./plop-templates/component/prompt')
module.exports = function(plop) {
plop.setGenerator('component', componentGenerator)
}