命令行一键生成vue项目相关模块文件

vue项目中(基于vue-cli脚手架),新建模块时必然伴随新建vue文件夹、router文件、api文件,一阵复制粘贴噼里啪, low且繁琐。 本章探讨基于node实现一键生成模块seed(模板)文件。

需求分析

我们的预期是执行node命令,生成以下文件
src > views > 模块文件夹 > index.vue + children文件夹 + commons文件夹
src > router > 模块文件

其中index.vue、router.js设置固定模板。

实现

配置文件,设置需要生成的文件夹名、路径以及所需要的模板。

1
2
3
4
5
6
7
8
9
10
11
12
// pathConfig/index.js
/**
 *  @param {*} fileName
 *  @param {*} filePath
 *  @param {*} fileTemplate
 */
const dirAndPath = {
  router: ['router', './view.js'],
  views: ['views', './view.js']
};

module.exports =  dirAndPath;

模板文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// pathConfig/view.js   vue文件所需要的模板
const vueFile = module => (`




`)

module.exports = vueFile;

然后是router需要的模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// pathConfig/router.js    路由文件所需要的模板
const routerFile = module => (`
export default [
  {
    path: '/${module}',
    name: '',
    redirect: '/${module}',
    component: () => import('@/views/frame/Frame'),
    children: [
      {
        path: '',
        fullPath: '',
        name: '',
        component: () => import('@/views/${module}/index')
      }
    ]
  }
]
`)
module.exports = routerFile;

 

最后是node文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const filesArr = require('./pathconfig')
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const reslove = file => path.resolve(__dirname, '../../src', file)
const errorLog = error => console.log(chalk.red(`${error}`))
const defaultLog = log => console.log(chalk.green(`${log}`))
const files = Object.keys(filesArr);
const viewsFile = require('./pathconfig/view')
const routerFile = require('./pathconfig/router')


let rootPath = {};

for (let item in filesArr){
  rootPath[item] = reslove(filesArr[item][0])
}

// module-method map
let generates = new Map();

let map = [];
files.forEach(item => {
  let i = [
    item,
    async (module) => {
      switch (item) {
        case 'views':
          const filePath = path.join(rootPath[item], module)
          const vuePath = path.join(filePath, '/index.vue')
          // commons module
          const commonsPath = path.join(filePath, 'commons')
          const commonsIndex = path.join(commonsPath, '/index.vue')

          // children module
          const childrenPath = path.join(filePath, 'children')
          const childrenIndex = path.join(childrenPath, '/index.vue')

          await generateFile(vuePath, viewsFile(module), filePath)
          await generateFile(commonsIndex, viewsFile(module), commonsPath)
          await generateFile(childrenIndex, viewsFile(module), childrenPath)
          break;
        case 'router':
          const routerPath = path.join(rootPath[item], `/${module}.js`)
          await generateFile(routerPath, routerFile(module))
          break;
      }
    }
  ];
  map.push(i)
})

map.forEach(
  ([key, value]) => generates.set(key, value)
);
/**
 * generate file
 * @param {*} filePath 
 * @param {*} content 
 * @param {*} dirPath 
 */
const generateFile = async (filePath, content, dirPath = '') => {
  try {
    // create file if file not exit
    if (dirPath !== '' && ! await fs.existsSync(dirPath)) {
      await fs.mkdirSync(dirPath)
      defaultLog(`created ${dirPath}`)
    }
    if (! await fs.existsSync(filePath)) {
      // create file
      await fs.openSync(filePath, 'w')
      defaultLog(`created ${filePath}`)
    }
    await fs.writeFileSync(filePath, content, 'utf8')
  } catch (error) {
    errorLog(error)
  }
}

defaultLog(`请输入模块名称(英文):`)

process.stdin.on('data', (chunk) => {
  try {
    defaultLog(chunk)
    chunk = chunk.slice(0, -1) // delete /n
    defaultLog(`new module name is ${chunk}`)
    files.forEach(async (el, index) => {
      // 执行创建语句
      await generates.get(`${el}`).call(null, chunk.toString())
      if (index === files.length - 1) {
        process.stdin.emit('end')
      }
    })
  } catch (error) {
    errorLog(error)
  }
})

process.stdin.on('end', () => {
  defaultLog('create module success')
})

 

实现的结果如下

你可能感兴趣的:(node)