在vue项目中,自动生成路由
安装plop
yarn add plop --dev
package.json中添加
"scripts": {
"plop": "plop"
}
运行直接 npm run plop
新建 plopfile.js
module.exports = function (plop) {
/*plop.setGenerator('component', {
description: '组件视图',
prompts: [{
type: 'input',
name: 'test',
message: 'testController'
}],
actions: [{
type: 'add',
path: 'src/components/main/report/testController.vue',
templateFile: 'src/components/main/report/test.vue'
}]
})*/
const path = '{{path}}'
const filePath = '{{filePath}}'
plop.setGenerator('router', {
description: '路由生成器',
prompts: [{
type: 'list',
name: 'rootPath',
message: '生成路由的目录',
choices: [
'router'
]
}, {
type: 'input',
name: 'path',
message: '路由的路径',
validate: (value) => {
return !value ? '请输入路由地址' : true;
}
},{
type: 'input',
name: 'filePath',
message: '目录路径',
validate: (value) => {
return !value ? '请输入目录路径' : true;
}
}],
actions: [{
type: 'modify',
path: 'src/router/index.js',
pattern: /\/\/ ---ROUTER_IMPORT---/g,
template: `{path: '${path}', name: '/main/${path}', component: () => import('src/components/main/${filePath}/${path}')},
// ---ROUTER_IMPORT---` // 这个是查找文件插入位置的标识
}]
})
}
!!! 在 router.js 添加 一个标记,标记目的是为了路由文件插入的位置