plop js 模板工具

2019-12-02  本文已影响0人  copyLeft
## plop 模板工具

概述

plop 模板生成cli

安装

// 全局安装
npm i -g plop

// 本地安装
npm i --save-dev plop

配置文件

// 更目录创建文件 plopfile.js  plop将已该文件作为执行入口

// 导出执行函数
module.exports = function(plop){

    plop.getGenerator("模板名称", {

        description: "操作描述",
        prompts: [], // 交互提示
        actions: [] // 执行操作
    })

}

基础使用

// plopfile.js

module.exports = function(plop){

   plop.getGenerator("vue基础模板", {
       description: '创建vue文件',
       prompts: [
           {
               type: 'input',  // 交互类型
               name: 'name',   // 参数名称
               message:'请输入文件名称' // 交互提示
           },
           {
               type: 'input',
               name: 'path',
               message: '请输入文件创建目录'
           }
       ],
       actions: [
           {
               type: 'add', // 动作类型
               path: '{{ path }}/{{ name }}.vue', // '{{  }}' 双大括号内设置动态参数
               templateFile: 'plop-templates/views/vue.hbs' // 模板文件地址, 使用hbs文件
           }
       ]

   })
}

// plop-templates/views/vue.hbs

<template>
    <div class='cmp-{{ name }}' >
    </div>
</template>
<script>
export default {
    name: '{{ name }}'
}
</script>
<style>
</style>

plop 命令参数

// 执行指定配置
plop 配置名称

// 执行指定配置并设置参数
plop 配置名称 输入参数

// 执行 plopfile 文件
--plopfile 文件路径

// 设置工作路径
--cwd

// 帮助
-h, --help

// 全局初始化
-i, --init

// 显示版本
-v, --version

generator 生成器 API

生成器, 用来生成执行文件模板或向文件中加入模板信息

默认 action API

模块分组

我们可将多个 配置分配到多个文件中单独管理

//  module/view/prompt.js 页面模板
const conf = {
    description: "view template",
    prompts: [
        {
            type: 'input',
            name: 'name',
            message: 'file name',
        }
    ],
    actions: data => {

        const name = '{{name}}'
        return [
            {
                type: 'add',
                path: `template/${name}.vue`,
                templateFile: 'plop-templates/view/index.hbs',
            }
        ]

    }
}

module.exports = function (plop){
    plop.setGenerator('view', conf)
}

//  module/components/prompt.js 组件模板
const conf = {
    description: "cmp template",
    prompts: [
        {
            type: 'input',
            name: 'name',
            message: 'file name',
        }
    ],
    actions: data => {

        const name = '{{name}}'
        return [
            {
                type: 'add',
                path: `template/${name}.vue`,
                templateFile: 'plop-templates/cmp/index.hbs',
            }
        ]

    }
}

module.exports = function (plop){
    plop.setGenerator('view', conf)
}

// root/plopfile.js 
const viewCallback = require('./plop-templates/view/prompt')
const cmpCallback = require('./plop-templates/cmp/prompt')

module.exports = function(plop){
    cmpCallback(plop)
    viewCallback(plop)
}

其他

上一篇 下一篇

猜你喜欢

热点阅读