前端项目工程化 -- 脚手架 Plop 的使用

Plop是一个小而美的脚手架工具

Plop一般不单独使用,而是集成到项目中,帮助我们根据模板批量生成文件

Plop怎么使用?

  • 安装

yarn add plop --dev

  • 在项目根目录下添加plop的入口文件plopfile.js
// plopfile.js样例代码
module.exoirts=plop=>{
  // 设置名为component的生成器
  plop.setGenerator('component',{
    description:'create a component',
    // 用户交互
    prompt:[
      {
        type:'input',//让用户输入回答问题
        name:'name',
        message:'component name?',
        default:'MyComponent'
      }
    ],
    // 用户交互完成后执行的动作
    actions:[
      {
        type:'add',
        path:'src/componants/{{name}}/{{name}}.js',
        templateFile:'plop-templates/component.hbs'//此处模板需要在项目根目录中添加
      },
      {
        type:'add',
        path:'src/componants/{{name}}/{{name}}.css',
        templateFile:'plop-templates/component.css.hbs'//此处模板需要在项目根目录中添加
      },
      {
        type:'add',
        path:'src/componants/{{name}}/{{name}}.test.js',
        templateFile:'plop-templates/component.test.hbs'//此处模板需要在项目根目录中添加
      }
    ]
  }
}

添加模板文件

在项目根目录中添加plop-templates文件夹,并添加文件:

  • components.hbs
  • components.css.hbs
  • components.test.hbs

文件中可以使用handlebars模板引擎语法

测试使用

在项目目录打开终端,输入yarn plop component,根据提示输入component的名称,比如"componenttest",就会在项目的component目录中添加文件夹componenttest,并生成模板文件对应类型的文件以及文件内容基础内容

原文地址:https://www.cnblogs.com/MissSage/p/14899459.html