Plop
uniapp编辑器hbuilder的模板创建不是很方便,故引入plop工具优化。
什么是Plop?
Plop是一个微型的自动化脚手架工具,它可以创建页面、组件等模板到代码目录中,避免重复复制代码。
安装使用
一般不会单独使用,而会集成在项目中。
- 安装
$ yarn add plop -D
- 在项目根目录创建plopfile.js文件,这个文件是配置的入口文件
module.exports = (plop) => {
plop.setWelcomeMessage("请选择需要创建的模板:");
plop.setGenerator("page", require("./plop-tpls/component/prompt"));
};
- 为创建方便在根目录创建plop-tpls文件夹管理模板
$ mkdir plop-tpls
$ mkdir component
# 交互配置
$ touch prompt.js
# 模板文件
$ touch index.hbs
- prompt.js
这个文件返回三个配置项
| Property | Type | Description |
|---|---|---|
| description | [String] | 模板名称介绍 |
| prompts | Array | 交互式提问 |
| actions | Array | 事件 |
其中prompts主要是引入inquirer库,配置可参考[InquirerQuestion]
action可配置参数如下,其他参考[actionconfig]
| Property | Type | Default | Description |
|---|---|---|---|
| type | String | 交互类型(add / modify / adMany ...) | |
| data | Object / Function | {} | 可注入模板的数据,可与提问数据混合 |
| templateFile | Sting | 模板文件路径 |
// prompt.js
const fs = require('fs')
const path = require('path')
function getFolder(cpath) {
let components = []
const files = fs.readdirSync(cpath)
files.forEach(function (item) {
let stat = fs.lstatSync(path.join(cpath, item))
if (stat.isDirectory() === true && item != 'components') {
components.push(path.join(cpath, item))
components.push.apply(components, getFolder(path.join(cpath, item)))
}
})
return components
}
module.exports = {
description: '创建组件',
prompts: [
{
type: 'confirm',
name: 'isGlobal',
message: '是否为全局组件',
default: false,
},
{
type: 'list',
name: 'path',
message: '请选择组件创建目录',
choices: getFolder('src/pages'),
when: (answers) => !answers.isGlobal,
},
{
type: 'input',
name: 'name',
message: '请输入组件名称',
validate: (v) => (!v || v.trim === '' ? '组件名称不能为空' : true),
},
],
actions: (data) => {
let path = ''
if (data.isGlobal) {
path = 'src/components/{{ dashCase name }}/ {{ dashCase name }}.vue'
} else {
path = `${data.path}/components/{{ properCase name }}.vue`
}
const actions = [
{
type: 'add',
path: path,
templateFile: 'plop-tpls/component/index.hbs',
},
]
return actions
},
}
- index.hbs
模板中的 properCase 为变更 name 命令的显示规则大驼峰,以下为所有的规则
- camelCase: changeFormatToThis
- snakeCase: change_format_to_this
- dashCase/kebabCase: change-format-to-this
- dotCase: change.format.to.this
- pathCase: change/format/to/this
- properCase/pascalCase: ChangeFormatToThis
- lowerCase: change format to this
- sentenceCase: Change format to this,
- constantCase: CHANGE_FORMAT_TO_THIS
- titleCase: Change Format To This
文件夹中使用的变量,用 {{}} 包裹
<template>
<view >
</view>
</template>
<script>
export default {
name: "{{ properCase name }}"
props: {},
data() {
return {}
},
methods: {}
}
</script>
<style lang="scss" scoped>
</style>
实际使用
- 选择模板
- 交互选择
- 生成模板