Plop基础使用和脚手架工作原理

简介

plop可以通过命令行去生成、处理文件模板代码等,从而简化项目中的手动操作

使用
  • 安装plop模块yarn add plop --dev

  • 新建plopfile.js文件,plopfile工作入口文件

  • 定义plopfile.js脚手架任务

    // 接收plop对象,用于创建生成器任务
    module.exports = (plop) => {
      // 可以对传入参数进行处理 用法{{ upperCase name }}
      plop.setHelper('upperCase', (txt) => {
        return txt.charAt(0).toUpperCase() + txt.substr(1)
      })
      // param 生成器名称 生成器配置选项
      plop.setGenerator('component', {
        description: '创建新路由',
        prompts: [
          {
            type: 'input',
            name: 'name',
            message: '组件名',
            default: 'MyComponent',
          },
          // 选择器
          {
            type: 'list',
            name: 'module',
            message: '选择创建文件到下面哪个文件夹',
            choices: ['cmdb', 'monitor', 'resource', 'support', 'system'],
          },
        ],
        actions: [
          {
            type: 'add', // 代表添加全新文件
            path: `src/views/{{module}}/{{name}}/{{upperCase name}}.vue`,
            templateFile: 'plop-templates/component.vue.hbs',
          },
          {
            type: 'add', // 代表添加全新文件
            path: 'src/views/{{module}}/{{name}}/index.js',
            templateFile: 'plop-templates/component.hbs',
          },
          // 修改使用modify
          // pattern正则表达式 用它来匹配目标文件追加的位置
          // template后面需添加$1,$1是pattern正则括号内匹配到的字符串,当发生替换时,占位符会连同模板文本一起替换掉目标文件中的占位符,所以这个占位符会一直存在于目标文件中,方便后续的追加
          {
            type: 'modify',
            path: 'src/utils/routerUtil.js',
            pattern: /(\/\/ ...more 此行不要删除 plop创建模板要使用)/gi,
            template: "{{name}}: () => import('@views/{{module}}/{{name}}'),\r\n  $1",
          },
        ],
      })
    }
    
    
  • 添加plop-templates文件夹,用于存放模板文件,模板文件需要使用hbs

    <template>
      <div></div>
    </template>
    
    <script>
      export default {
        name: '{{ upperCase name }}'
      }
    
    </script>
    <style>
    </style>
    
image-20210118200103371.png
  • 使用yarn plop component(对应生成器的名字)运行脚手架任务,生成特定文件

  • 最后添加到Npm Scripts中,方便使用

脚手架工作原理
  1. yarn init --yes初始化项目

  2. 在package.json中添加bin字段,指定cli应用入口文件

  3. 创建cli.js,添加头`#!/usr/bin/env node`

  4. 使用yarn link将当前模块link到全局,供其他使用

  5. 创建templates模板目录,引入模板文件

  6. 使用inquirer模块生成命令行交互询问,yarn add inquirer

  7. 获取用户回答,将模板文件复制到目标文件,生成项目目录

    #!/usr/bin/env node
    
    // Node Cli应用入口文件必须要有这个文件头
    
    // 脚手架工作流程
    // 1.通过命令行交互询问用户问题
    // 2.根据用户回答的结果生成文件
    
    const inquirer = require('inquirer')
    const fs = require('fs')
    const path = require('path')
    const ejs = require('ejs')
    
    inquirer
      .prompt([
        {
          type: 'input',
          name: 'name',
          message: 'Project name',
        },
      ])
      .then((answer) => {
        // 根据用户回答结果生成文件
    
        // 模板目录
        const tempDir = path.join(__dirname, 'templates')
        // 目标目录
        const destDir = process.cwd()
    
        // 模板文件转换到目标文件
        fs.readdir(tempDir, (err, files) => {
          if (err) throw err
          // 此时获取的文件是相当于templates下的相对路径
          files.forEach((file) => {
            // 通过模板引擎渲染相对路径所对应的文件
            ejs.renderFile(path.join(tempDir, file), answer, (err, result) => {
              if (err) throw err
              // 将结构写入目标文件
              fs.writeFileSync(path.join(destDir, file), result)
            })
          })
        })
      })
    
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容