搭建了一个前端脚手架工具,模板集成了 vite、vue3、vue-router、vuex、axios

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
#!/usr/bin/env node
const { program } = require('commander')
const inquirer = require('inquirer')
const chalk = require('chalk')
const fs = require('fs')
const path = require('path')
const memFs = require('mem-fs')
const editor = require('mem-fs-editor')
const store = memFs.create();
const memFsEditor = editor.create(store)

let CWD = process.cwd()
let ROOT_PATH

program.version(require('../package.json').version)

program
.command('create <name>')
.alias('i')
.description('init a vue project')
.action((name) => {

const files = fs.readdirSync(CWD)
if (files.length !== 0) { // 当前文件夹不为空
inquirer.prompt([
{
type: 'confirm',
name: 'isNotEmpty',
message: `destination is not empty, create a folder '${name}'?`
}
]).then(async res => {
if (res.isNotEmpty === true) {
ROOT_PATH = path.resolve(CWD, name)
if (fs.existsSync(ROOT_PATH)) { // 存在同名文件夹
console.log(chalk.red(`folder '${ROOT_PATH}' already exists`))
fileTree(ROOT_PATH)
} else {
fs.mkdirSync(ROOT_PATH)
memFsEditor.copyTpl(path.resolve(__dirname, '../templates'), ROOT_PATH, { name })
memFsEditor.commit(() => {
printLog(name)
})
}
}
})
} else {
ROOT_PATH = CWD
memFsEditor.copyTpl(path.resolve(__dirname, '../templates'), ROOT_PATH, { name })
memFsEditor.commit(() => {
printLog()
})
}
})

function fileTree(filePath) {
const files = fs.readdirSync(filePath)
files.forEach(file => {
let fileDir = path.resolve(filePath, file)
const stats = fs.statSync(fileDir)
let isFile = stats.isFile()
let isDir = stats.isDirectory()
if (isFile) {
console.log(' ' + chalk.greenBright('create :'), path.relative(ROOT_PATH, fileDir))
}
if (isDir) {
fileTree(fileDir)
}
})
}

function printLog(name) {
fileTree(ROOT_PATH)
console.log(`
install dependencies:
${chalk.green(`> cd ${name ? './' + name : '.'} && npm install`)}
run the app:
${chalk.green('> npm run dev')}
`)
}

program.parse()
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
PS F:\cli-demo> oyal-cli create cli-demo
create : index.html
create : package-lock.json
create : package.json
create : public\favicon.ico
create : README.md
create : src\api\index.js
create : src\App.vue
create : src\assets\logo.png
create : src\config\index.js
create : src\main.js
create : src\permission.js
create : src\router\index.js
create : src\store\actions.js
create : src\store\getters.js
create : src\store\index.js
create : src\store\mutations.js
create : src\utils\request.js
create : src\views\About.vue
create : src\views\Home.vue
create : vite.config.js
create : webstorm.config.js

install dependencies:
> cd . && npm install
run the app:
> npm run dev