高效工作神器——plop

1,455 阅读2分钟

今天在工位上看见旁边的小伙伴在代码构建上 crtl+c => ctrl +v,着实让我心疼了几秒。都 2020 年了,怎么还有人不知道使用 plop。

看在上周大份羊汤的份上,今天就分享下这个小巧高效的工具。用起来!

# 安装

要把大象放冰箱使用 plop,总共分几步?

首先,第一步,安装 plop。

具体怎么装我就不说了,大家直接去官网扫一眼。

官网:github.com/plopjs/plop

安装成功之后,要在项目目录下创建一个 plopfile.js 的文件。

//plopfile.jsmodule.exports = function(plop) {
    plop.setGenerator("component",{
        "description":"generator a component",
        "prompts":[
            {
                type: 'input',    //提示信息的类型 input 输入 checkbox 选择 list 列表
                name: 'template',  //字段的名称
                message: 'controller name please'  //提示的信息说明
            }
        ], 
       actions:function(data){
            console.log(data)
            const configs = [
                {
                type:"add",
                path:"views/{{template}}.vue",
                templateFile:"plop-template/template.hbs"
                }
            ]
            return configs;
        }
    })
}

plopfile.js 内容如上,接下来就是对 plop API 的系列介绍了。

# API

首先在函数内的 setGenerator() 设置生成器。

它内部集成了 inquire.js 这种一问一答的交互模式,同时这个 setGenerator 的第一个参数就是我们的生成器指令。这个 demo 定义了一个 component 指令,使用的时候在终端输入 `plop component` 。

第二个参数就是接下来我们关于这个指令的配置项。

prompts 翻译过来有提示的意思。

  • type 何种类型输入,一般有 input (输入) checkbox(多选)list(列表) confirm(确认)

  • name 输入的值所对应的键,如果输入 cwj,那么这个最后的形式就是 {"template":"cwj"}

  • message 提示信息

  • prompts 的其他属性的用法请参考 github.com/SBoudrias/I…

actions 叫行为,也就是说接下来要做的一系列动作是什么。

  • type 行为的类型,常用 add modify

  • path 生成的新文件所存放的位置

  • templateFile 模板文件的路径

  • data 需要传入 handlebar 文件的数据 其他属性参数地址github.com/plopjs/plop…

我们再回到 main-methods 这个栏目下 github.com/plopjs/plop…

这里面的 api 我们简单看看。

setGenerator 我们就不看了。setHelper 直接对应于 handlebars 方法registerHelper。

因此,如果你想要知道它的用法,你需要熟悉 Handlebars.registerHelper 的用法。

地址:handlebarsjs.com/zh/guide/#%…

//plopfile.js
const setView = require("./plop-template/views/prompt")
module.exports = function (plop) {
    plop.setHelper('upperCase', function (text) {
        return text.toUpperCase();
    });
    plop.setGenerator("view",setView)
}

在 handlebars 文件下的内容就可以直接使用这个 Handlebars.registerHelper 了。

//.hbs
{{#if template}}
<template>
    <div>
        {{upperCase view}}   // view 就是这个助手的参数
    </div>
</template>
{{/if}}
{{#if script}}
<script>
    export default {
        data:()=>{
            return {
            }
        }
    }
</script>
{{/if}}
{{#if style}}
<style scoped>
</style>
{{/if}}

当然,你可能对这个整体案例的结构不是很清楚,不要紧,我已经上传到 git 仓库。

地址:github.com/cuiweijun/p…

这样,一个小型的快速构建项目的工具就成功了!