前端代码自动生成工具plop

1,668 阅读2分钟

在前端开发中,经常会创建一些常用的文件,这些文件具有类似的模板,因此可以通过plop这个工具自动批量生成文件。

安装plop

  • 安装到项目
 npm install --save-dev plop

配置入口文件

Plop入口文件,需要导出一个函数,此函数接收一个Plop对象,用于创建生成器任务。新建三个文件夹入口,分别是page、component、store,分别对象项目src下的views、components、store文件夹,如需其他可以扩展。

  • 在项目根目录下新建plopfile.js文件

    // plopfile.js
    module.exports = function(plop) {
        plop.setWelcomeMessage('请选择需要创建的模式:')
        plop.setGenerator('page', require('./plop-templates/page/prompt'))
        plop.setGenerator('component', require('./plop-templates/component/prompt'))
        plop.setGenerator('store', require('./plop-templates/store/prompt'))
    }
    

配置模板文件

在根目录下配置模板文件,用于自动生成代码的逻辑及模板母版。

  • 根目录下新建plop-template文件夹

  • 分别在上述文件夹下新建page、component、store文件夹

  • page文件夹下新建prompt.js文件,这是关键文件,主要负责定位到views文件夹,并且匹配对应的模板生成新文件。

    // prompt.js
    const path = require('path')
    const fs = require('fs')
    ​
    function getFolder(path) {
        let components = []
        const files = fs.readdirSync(path)
        console.log(files)
        // eslint-disable-next-line space-before-function-paren
        files.forEach(function (item) {
            let stat = fs.lstatSync(path + '/' + item)
            if (stat.isDirectory() === true && item != 'components') {
                components.push(path + '/' + item)
                components.push.apply(components, getFolder(path + '/' + item))
            }
        })
        return components
    }
    ​
    module.exports = {
        description: '创建页面',
        prompts: [
            {
                type: 'list',
                name: 'path',
                message: '请选择页面创建目录',
                choices: getFolder('src/views')
            },
            {
                type: 'input',
                name: 'name',
                message: '请输入文件名',
                validate: v => {
                    if (!v || v.trim === '') {
                        return '文件名不能为空'
                    } else {
                        return true
                    }
                }
            }, {
                type: 'input',
                name: 'template',
                message: '请输入模板名称',
            }
        ],
        actions: data => {
            let relativePath = path.relative('src/views', data.path)
            const actions = [
                {
                    type: 'add',
                    path: `${data.path}/{{dotCase name}}.vue`,
                    templateFile: 'plop-templates/page/{{dotCase template}}.hbs',
                    data: {
                        componentName: `${relativePath} ${data.name}`
                    }
                }
            ]
            return actions
        }
    }
    ​
    

    这一步中需要特别注意的是templateFile这个配置。比如有这么个场景,我们在实际开发中,除了初始化vue文件的基本基础骨架以外,还有可能会抽取出来若干个业务模板,就是带有一定逻辑的业务代码,这时我们就可以抽象出多个hbs文件,分别对应不同的业务模板,比如index.hbs、index1.hbs等等。然后在prompts数组中添加一个提示项: {            type: 'input',            name: 'template',            message: '请输入模板名称',       } 在templateFile中配置动态变量,变量名为上述的template的值,即命令行输入的模板名字。这样就可以根据模板名称,生成不同的vue文件。

  • page下新建index.hbs文件,这是生成模板的母版。即通过命令行自动生成的文件模板。

    <template>
        <div>
            页面内容区域
        </div>
    </template><script>
    export default {
        name: '{{ properCase componentName }}',
        data() {
            return {}
        },
        mounted() {},
        methods: {}
    }
    </script><style lang="scss" scoped>
    // scss
    </style>

在package.json中设置命令行脚本,用于启动plop

  • 脚本名称自定义,值为plop即可

      "scripts": {
        "new": "plop"
      },
    

启动plop

vscode控制台输入npm run new即可,比如选择page,回车,输入文件名,比如test,回车:

1628751407(1).png

则在views/account文件下新建了一个test.vue文件。