Plop 让你告别复制粘贴

2,422 阅读3分钟

什么是plop

plop是一个小工具,让你可以在项目中方便的生成各种各样模板代码代码生成工具。

使用

  1. yarn add plop -D

  2. 创建一个plopfile.js 在你的项目根目录中,plop会根据你创建的plopfile.js的配置自动生成文件

    module.exports = function (plop) {
        // 创建了basics的动作
        plop.setGenerator('basics', {
            // 描述
            description: 'this is a skeleton plopfile',
            // 接受用户的输入,input是输入,list是选择,这里的type的类型是基于inquirer.js的prompts
            prompts: [{
                type: 'input',
                name: 'name',
                message: 'controller name please'
            }],
            // add 是添加一个文件,name是上面输入的name名字
            actions: [{
                type: 'add',
                path: 'src/{{name}}.js',
                templateFile: 'plop-templates/controller.hbs'
            }]
        });
    };
    ​
    
  3. 完成之后,就可以在package.json里边添加plop命令,执行yarn run plop就ok了

主要方法

主要方法参数返回描述
setGeneratorstring,GeneratorConfigGeneratorConfig生成一个样板文件
setHelperstring,func注册一个函数,可以在模板文件中使用
setPartialstring,string注册一个代码片段
setActionTypestring,CustomAction注册一个自己的action
setPromptstring,inquirePromt注册一个自己的prompt
loadArray[String],Object,ObjectLoad其他的plopfile设置

SetHelper

setHelper就是创建一个可以在模板中使用的函数,比如我的项目中是这么使用的

module.exports = (plop) => {
  plop.setHelper('upperCase', (string) => string.charAt(0).toUpperCase() + string.slice(1));
  // plop.setGenerator('component', zsjgenerateCompConfig);
  // plop.setGenerator('zsjContainer', zsjgenerateContainerConfig);
  // plop.setGenerator('zsjReducers', zsjReducersConfig);
  // plop.setGenerator('test', zsjTestConfig);
  // plop.setGenerator('list',xjwGenerateList)
};

这样就是全局注册了一个upperCase函数,我们就可以在模板中使用了

function {{upperCase containerName}}(props) {

setPartial

这个方法是注册一个全局的代码片段

module.exports = function (plop) {
    plop.setPartial('myTitlePartial', '<h1>{{titleCase name}}</h1>');
    // used in template as {{> myTitlePartial }}
};

setGenerator

主要方法,用来生成配置,比如我的配置如下

module.exports = (plop) => {
  plop.setHelper('upperCase', (string) => string.charAt(0).toUpperCase() + string.slice(1));
  plop.setGenerator('component', zsjgenerateCompConfig);
  plop.setGenerator('zsjContainer', zsjgenerateContainerConfig);
  plop.setGenerator('zsjReducers', zsjReducersConfig);
  plop.setGenerator('test', zsjTestConfig);
  plop.setGenerator('list', xjwGenerateList);
};

主要动作

这里的动作是指增加文件或者修改文件等操作

Add

添加文件

AddMany

一起增加多个文件

Modify

修改文件

Append

在一个文件后边增加内容

实战

创建组件模板

现在我们创建一个组件,一般都需要在某个目录下面创建一个index.jsx 和一个index.scss,然后修改组件名称,这样比较麻烦,我们可以使用plop实现一键创建。

创建组件.gif

当然这里你可以根据自己的需求设置模板内容,也可以设置index.scss的模板内容

自动引入组件

另外一个场景就是我们经常自动创建完成一个组件的时候,需要在某些文件中引入,然后在render中写入组件,这里我们也可以使用plop来自动完成。

这里首先在我们刚才创建的组件里边加入两行需要替换的字符串// import comp 和

{/* comp conent */}, 可以看gif

122.gif

这里只是插入了一个文件,如果在项目中当你创建一个文件,需要固定的插入到几个文件的时候,你就可以使用这个方法,同时插入到多个文件中去,而不需要再重复的打开每个文件自己手动插入了。

有了创建和修改文件,你就可以根据自己的项目组合出各种不同的代码模板,自动生成,当然这个也可以结合vscode的代码片段一起使用,事半功倍。