UNPKG

2.52 kBJavaScriptView Raw
1const Generator = require('yeoman-generator')
2const yosay = require('yosay')
3const utils = require('../app/utils');
4
5
6module.exports = class extends Generator {
7 constructor (args, opts) {
8 super(args, opts)
9
10 this.modules = this.config.getAll().modules;
11 }
12
13 initializing () {
14 this.log(yosay('Iniciando generator de rotas'))
15 }
16
17 prompting () {
18 const restrictedNames = this.modules.join('|')
19 return this.prompt([{
20 type: 'input',
21 name: 'routeName',
22 message : `Escolha o nome da rota (Rotas existentes: ${restrictedNames}):`,
23 default: 'Teste'
24 }]).then(answers => {
25 this.routeName = answers.routeName
26
27 const modules = this.config.getAll().modules;
28
29 if (modules.indexOf(this.routeName) > 0) {
30 this.routeName = [this.routeName, +new Date()].join('')
31 }
32
33 this.lrouteName = this.routeName.toLowerCase();
34 modules.push(this.lrouteName)
35
36 this.config.set({ modules })
37 this.config.save()
38 })
39 }
40
41 writing() {
42 const routerPath = this.destinationPath('src/router/index.js')
43 const modulePath = this.destinationPath('src/vuex/modules.js')
44 const baseName = utils.getBaseName(this.lrouteName)
45 const relativePath = utils.getRelativePath(this.lrouteName, 'app', '')
46
47 // Copy the route and vuex-module template
48 this.fs.copyTpl(
49 this.templatePath('route.vue'),
50 this.destinationPath(`src/app/${this.lrouteName}/main.vue`),
51 {
52 lmoduleName: this.lrouteName,
53 moduleName: this.routeName
54 }
55 )
56
57 this.fs.copy(
58 this.templatePath('vuex'),
59 this.destinationPath(`src/app/${this.lrouteName}/vuex`)
60 )
61
62 // Create the vuex module import declaration
63 const importString = `import ${this.lrouteName} from '../app/${this.lrouteName}/vuex'`
64 const importDeclaration = (utils.readString(importString)).body[0]
65
66 const exportSpecifier = {
67 type: 'ExportSpecifier',
68 local: { type: 'Identifier', name: this.lrouteName },
69 exported: { type: 'Identifier', name: this.lrouteName }
70 }
71 const tree = utils.read(modulePath)
72
73 let position = 0
74
75 for (const item of tree.body) {
76 if (item.type === 'ImportDeclaration') { position += 1; }
77 else if (item.type === 'ExportNamedDeclaration') {
78 console.log(item.specifiers)
79 item.specifiers.push(exportSpecifier)
80 }
81 }
82
83 // Insert the module after the last import
84 tree.body.splice(position, 0, importDeclaration)
85
86 utils.write(modulePath, tree)
87 }
88}