plop简单实践

986 阅读3分钟

前言

我们日常开发中经常需要新建目录和文件,然而这些东西是高度相同,而我们却需要重复的进行。原始的做法则是使用万能的 Ctrl + cCtrl + v,来一个个手动创建,例如我们在 VSCode 中开发微信小程序,每当我们新建一个页面或者一个组件的时候我们都需要新建 **.wxml**.js**.wxss**.json 这样四个文件,然后再根据组件或者页面动态创建内部的变量和 class 名。这样严重降低了我们的开发效率,而 plop 工具就能很好的帮忙我们解决这些繁琐而又简单的事情。

Plop 是什么?

Plop is what I like to call a "micro-generator framework." Now, I call it that because it is a small tool that gives you a simple way to generate code or any other type of flat text files in a consistent way. You see, we all create structures and patterns in our code (routes, controllers, components, helpers, etc). These patterns change and improve over time so when you need to create a NEW insert-name-of-pattern-here, it's not always easy to locate the files in your codebase that represent the current "best practice." That's where plop saves you. With plop, you have your "best practice" method of creating any given pattern in CODE. Code that can easily be run from the terminal by typing plop. Not only does this save you from hunting around in your codebase for the right files to copy, but it also turns "the right way" into "the easiest way" to make new files.

这是 Plop 官网自身的介绍,简单翻译过来就是:
Plop 是一个小型的构建框架,它能通过终端命令快速创建你所需要的模板文件。
官网地址:plopjs.com/, 同时你需要了解下 .hbs 这样的语法。

使用

安装

使用 Plop 前,我们需要安装 Plop

// 此处使用全局安装
npm install -g plop

创建文件目录

然后我们新建测试目录,初始化 npm,并且创建 plopfile.js 文件,此文件为 Plop 的入口文件,类似 gulpfile.js

mkdir plop-demo
cd plop-demo

// 此处一路回车就可以了
npm init

目录结构如下图:

1.png

编写 plopfile.js 文件

// plopfile.js 文件
module.exports = plop => {
    // 第一个参数为 plop 子工程名,第二个参数为 plop 的配置参数
    plop.setGenerator('component', {
        // 工程描述(此处创建vue模板为例)
        description: 'Create a vue component',
        // 终端交互,收集用户输入信息
        prompts: [
            {
                type: 'input', // 交互类型
                name: 'name', // 当前交互的信息字段
                message: 'Component name', // 提示信息
                default: 'my-component' // 默认名称
            }
        ],
        // plop 的执行
        actions: [
            {
                type: 'add', // 方式(此为新建)
                path: 'src/components/{{name}}/{{name}}.vue', // 生成文件的路径
                templateFile: 'plop-templates/components/vue.hbs' // plop 模板路径
            }
        ]
    })
}

编写 vue.hbs 模板

<template>
  <div class="{{name}}">
    {{name}}组件
  </div>
</template>

<script>
export default {
  name: '{{name}}'
}
</script>

<style scoped>
.{{name}} {
  background-color: #f5f6f7;
}
</style>

修改 package.json 文件,并运行

修改 package.json 文件,创建快速构建命令

{
    ...
    scripts: {
        "vueComponent": "plop component"
    }
}

然后,在终端输入 npm run vueComponent 则可以快速创建 vue 的模板(此处只是举例说明,使用 vscode 的话直接创建 vscode 的代码片段更快),你会开到终端提示如下:

3.png

输入 Hello 组件名后,自动创建文件

4.png

创建后 Hello.vue 的文件内容

6.png

这样就能快速创建自己想要的文件和目录结构了。