1、实现交互式命令行
const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const execa = require('execa')
const Module = require('module')
const ejs = require('ejs')
const isManualMode = answers => answers.preset === '__manual__'
const context = path.resolve(__dirname, 'my-app')
const name = 'my-app'
const promptCompleteCbs = [
(answers, options) => {
if (answers.features.includes('vuex')) {
options.plugins['@vue/cli-plugin-vuex'] = {}
}
}
]
const defaultPreset = {
useConfigFiles: false,
cssPreprocessor: undefined,
plugins: {
'@vue/cli-plugin-babel': {},
'@vue/cli-plugin-eslint': {
config: 'base',
lintOn: ['save']
}
}
}
const presets = {
'default': Object.assign({ vueVersion: '2' }, defaultPreset),
'__default_vue_3__': Object.assign({ vueVersion: '3' }, defaultPreset)
}
const presetChoices = Object.entries(presets).map(([name, preset]) => {
let displayName = name
if (name === 'default') {
displayName = 'Default'
} else if (name === '__default_vue_3__') {
displayName = 'Default (Vue 3)'
}
return {
name: `${displayName}`,
value: name
}
})
const presetPrompt = {
name: 'preset',
type: 'list',
message: `Please pick a preset:`,
choices: [
...presetChoices,
{
name: 'Manually select features',
value: '__manual__'
}
]
}
let features = [
'vueVersion',
'babel',
'typescript',
'pwa',
'router',
'vuex',
'cssPreprocessors',
'linter',
'unit',
'e2e'
]
const featurePrompt = {
name: 'features',
when: isManualMode,
type: 'checkbox',
message: 'Check the features needed for your project:',
choices: features,
pageSize: 10
}
const prompts = [
presetPrompt,
featurePrompt
]
async function create () {
let answers = await inquirer.prompt(prompts);
console.log(answers)
}
create()
处理 preset 以及里面的 plugins
async function create () {
let answers = await inquirer.prompt(prompts);
console.log(answers)
let preset;
if (answers.preset !== '__manual__') {
preset = presets[answers.preset]
} else {
preset = {
useConfigFiles: false,
plugins: {}
}
}
promptCompleteCbs.forEach(cb => cb(answers, preset))
preset.plugins['@vue/cli-service'] = Object.assign({
projectName: name
}, preset)
}
构造一个package并且写入文件系统
async function writeFileTree (dir, files) {
Object.keys(files).forEach((name) => {
const filePath = path.join(dir, name)
fs.ensureDirSync(path.dirname(filePath))
fs.writeFileSync(filePath, files[name])
})
}
async function create () {
let answers = await inquirer.prompt(prompts);
console.log(answers)
let preset
if (answers.preset !== '__manual__') {
preset = presets[answers.preset]
} else {
preset = {
useConfigFiles: false,
plugins: {}
}
}
promptCompleteCbs.forEach(cb => cb(answers, preset))
preset.plugins['@vue/cli-service'] = Object.assign({
projectName: name
}, preset)
const pkg = {
name,
version: '0.1.0',
private: true,
devDependencies: {}
}
const deps = Object.keys(preset.plugins)
deps.forEach(dep => {
pkg.devDependencies[dep] = 'latest'
})
await writeFileTree(context, {
'package.json': JSON.stringify(pkg, null, 2)
})
}
安装依赖解析插件
function run (command, args) {
return execa(command, args, { cwd: context })
}
function loadModule (request, context) {
Module.createRequire(path.resolve(context, 'package.json'))(request)
}
async function resolvePlugins (rawPlugins, pkg) {
const plugins = []
for (const id of Object.keys(rawPlugins)) {
const apply = loadModule(`${id}/generator`, context) || (() => {})
let options = rawPlugins[id] || {}
plugins.push({ id, apply, options })
}
return plugins
}
async function create () {
let answers = await inquirer.prompt(prompts);
console.log(answers)
let preset
if (answers.preset !== '__manual__') {
preset = presets[answers.preset]
} else {
preset = {
useConfigFiles: false,
plugins: {}
}
}
promptCompleteCbs.forEach(cb => cb(answers, preset))
preset.plugins['@vue/cli-service'] = Object.assign({
projectName: name
}, preset)
const pkg = {
name,
version: '0.1.0',
private: true,
devDependencies: {}
}
const deps = Object.keys(preset.plugins)
deps.forEach(dep => {
pkg.devDependencies[dep] = 'latest'
})
await writeFileTree(context, {
'package.json': JSON.stringify(pkg, null, 2)
})
await run('npm', ['install'])
const plugins = await resolvePlugins(preset.plugins, pkg)
}
调用生成器函数
async function create () {
let answers = await inquirer.prompt(prompts);
console.log(answers)
let preset
if (answers.preset !== '__manual__') {
preset = presets[answers.preset]
} else {
preset = {
useConfigFiles: false,
plugins: {}
}
}
promptCompleteCbs.forEach(cb => cb(answers, preset))
preset.plugins['@vue/cli-service'] = Object.assign({
projectName: name
}, preset)
const pkg = {
name,
version: '0.1.0',
private: true,
devDependencies: {}
}
const deps = Object.keys(preset.plugins)
deps.forEach(dep => {
pkg.devDependencies[dep] = 'latest'
})
await writeFileTree(context, {
'package.json': JSON.stringify(pkg, null, 2)
})
await run('npm', ['install'])
const plugins = await resolvePlugins(preset.plugins, pkg)
const generator = new Generator(context, {
pkg,
plugins,
})
await generator.generate()
}
Generator 生成器
class Generator {
constructor (context, {
pkg = {},
plugins = [],
files = {}
}) {
this.context = context
this.plugins = plugins
this.pkg = Object.assign({}, pkg)
this.files = files
this.fileMiddlewares = []
const cliService = plugins.find(p => p.id === '@vue/cli-service')
this.rootOptions = cliService.options
}
async generate () {
await this.initPlugins()
}
async initPlugins () {
for (const plugin of this.plugins) {
const { id, apply, options } = plugin
const api = new GeneratorAPI(id, this, options, this.rootOptions)
await apply(api, options, rootOptions)
}
}
}
为每个插件创建一个GeneratorAPI对象
function extractCallDir () {
const obj = {}
Error.captureStackTrace(obj)
const callSite = obj.stack.split('\n')[3]
const namedStackRegExp = /\s\((.*):\d+:\d+\)$/
const anonymousStackRegExp = /at (.*):\d+:\d+$/
let matchResult = callSite.match(namedStackRegExp)
if (!matchResult) {
matchResult = callSite.match(anonymousStackRegExp)
}
const fileName = matchResult[1]
return path.dirname(fileName)
}
class GeneratorAPI {
constructor (id, generator, options, rootOptions) {
this.id = id
this.generator = generator
this.options = options
this.rootOptions = rootOptions
this.pluginsData = generator.plugins
}
_injectFileMiddleware (middleware) {
this.generator.fileMiddlewares.push(middleware)
}
_resolveData (additionalData) {
return Object.assign({
options: this.options,
rootOptions: this.rootOptions,
plugins: this.pluginsData
}, additionalData)
}
render (source, additionalData = {}, ejsOptions = {}) {
const baseDir = extractCallDir()
if (isObject(source)) {
this._injectFileMiddleware(files => {
const data = this._resolveData(additionalData)
for (const targetPath in source) {
const sourcePath = path.resolve(baseDir, source[targetPath])
const content = renderFile(sourcePath, data, ejsOptions)
if (Buffer.isBuffer(content) || content.trim()) {
files[targetPath] = content
}
}
})
}
}
}
真正执行中间件
class Generator {
constructor (context, {
pkg = {},
plugins = [],
files = {}
}) {
this.context = context
this.plugins = plugins
this.pkg = Object.assign({}, pkg)
this.files = files
this.fileMiddlewares = []
const cliService = plugins.find(p => p.id === '@vue/cli-service')
this.rootOptions = cliService.options
}
async generate () {
await this.initPlugins()
await this.resolveFiles()
}
async resolveFiles () {
const files = this.files
for (const middleware of this.fileMiddlewares) {
await middleware(files, ejs.render)
}
}
async initPlugins () {
for (const plugin of this.plugins) {
const { id, apply, options } = plugin
const api = new GeneratorAPI(id, this, options, this.rootOptions)
await apply(api, options, rootOptions)
}
}
}
最后写入文件系统
class Generator {
constructor (context, {
pkg = {},
plugins = [],
files = {}
}) {
this.context = context
this.plugins = plugins
this.pkg = Object.assign({}, pkg)
this.files = files
this.fileMiddlewares = []
const cliService = plugins.find(p => p.id === '@vue/cli-service')
this.rootOptions = cliService.options
}
async generate () {
await this.initPlugins()
await this.resolveFiles()
this.files['package.json'] = JSON.stringify(this.pkg, null, 2) + '\n'
await writeFileTree(this.context, this.files)
}
async resolveFiles () {
const files = this.files
for (const middleware of this.fileMiddlewares) {
await middleware(files, ejs.render)
}
}
async initPlugins () {
for (const plugin of this.plugins) {
const { id, apply, options } = plugin
const api = new GeneratorAPI(id, this, options, this.rootOptions)
await apply(api, options, rootOptions)
}
}
}
|