以前开发angular项目的时候,通过Angular CLI 创建一个组件,可以通过指令ng generate component "component-name",在终端运行这个命令,会创建一个以"component-name"为命名的文件夹,文件夹下包含以下:以component-name为命名的
组件文件<component-name>.component.ts
控制行为,
模板文件<component-name>.component.html
控制结构,
CSS 文件, <component-name>.component.css
控制样式
这是通过Angular CLI指令创建的方式,在使用Vue或React时,一般情况下我们都是使用手动创建的方式来创建xxx.vue组件等,以往使用过的vue-element-admin做项目,也是可以通过npm命令创建模板,那么尝试下将结合其创建模板的方式运用到我们自己的项目,以达到同样的效果
首先安装plop,创建plopfile.js及plop-template文件夹来实现自动创建项目文件
npm install --save-dev plop
复制代码
新建plopfile.js文件
const viewGenerator = require('./plop-templates/view/prompt')
const componentGenerator = require('./plop-templates/component/prompt')
const storeGenerator = require('./plop-templates/store/prompt.js')
module.exports = function(plop) {
plop.setGenerator('view', viewGenerator)
plop.setGenerator('component', componentGenerator)
plop.setGenerator('store', storeGenerator)
}
复制代码
并且在package.json中scripts中添加一行 "plop": "plop",后续做指令使用
新建plop-template文件夹,使用vue-element-admin的模板文件作使用,有兴趣的伙伴可以到花衩裤大佬的后台查看
以创建component为例 index.hbs为模板
{{#if template}}
<template>
{{!-- html --}}
<div />
</template>
{{/if}}
{{#if script}}
<script>
//script
export default {
name: '{{ properCase name }}',
props: {},
data() {
return {}
},
created() {},
mounted() {},
methods: {}
}
</script>
{{!-- style --}}
{{/if}}
{{#if style}}
<style lang="scss" scoped>
</style>
{{/if}}
复制代码
prompt.js为创建component组件时执行
const { notEmpty } = require('../utils.js')
module.exports = {
description: 'generate vue component',//描述
prompts: [{
type: 'input',//问题类型
name: 'name',//回应问题输入的答案,可做变量使用创建为组件名
message: 'component name please',//提示
validate: notEmpty('name')//校验方式
},
//其他模板内容选项,可选项
{
type: 'checkbox',
name: 'blocks',
message: 'Blocks:',
choices: [{
name: '<template>',
value: 'template',
checked: true
},
{
name: '<script>',
value: 'script',
checked: true
},
{
name: 'style',
value: 'style',
checked: true
}
],
validate(value) {
if (value.indexOf('script') === -1 && value.indexOf('template') === -1) {
return 'Components require at least a <script> or <template> tag.'
}
return true
}
}
],
actions: data => {
const name = '{{properCase name}}'
const actions = [{
type: 'add',
path: `src/components/${name}/index.vue`,//新增文件的路径
templateFile: 'plop-templates/component/index.hbs',//选择模板文件的路径
data: {
name: name,
template: data.blocks.includes('template'),
script: data.blocks.includes('script'),
style: data.blocks.includes('style')
}
}]
return actions
}
}
复制代码
当这些准备步骤完成就可以运行npm run plop来创建模板了,尝试新建helloworld试试~
那么helloworld组件就成功创建拉,模板自动化创建就完成啦,希望能由此提高生成力