UNPKG

@lvl/wxapp-cli

Version:

wxapp-cli

121 lines (106 loc) 2.95 kB
const inquirer = require('inquirer') const fse = require('fs-extra') const { cliRoot } = require('../config/wxapp-cli.config') const { execSync } = require('child_process') const presetPrompts = require('../prompt') const Generator = require('./generator.class') const EventEmitter = require('events') const chalk = require('chalk') const { hasGit, hasProjectGit, setProjectGit, logWithSpinner, stopSpinner, log } = require('../utils') const _hasGit = hasGit() module.exports = class Creator extends EventEmitter { constructor (name, ctx) { super() this.name = name this.ctx = ctx this.prompts = [] presetPrompts.forEach(prompt => { this.prompts.push(prompt) }) } async create (cliOptions = {}) { const { name, ctx } = this const { appName, templateName } = await inquirer.prompt(this.prompts) const tplModuleName = `@lvl/${templateName}` log() logWithSpinner(`创建项目目录 ${ctx}`) fse.mkdirsSync(ctx) logWithSpinner(`准备小程序模版 ${templateName}`) log() // install template module this.run(`npm install ${tplModuleName} --no-save --unsafe-perm`, { cwd: cliRoot, stdio: 'inherit' }) log() const initGit = this.shouldInitGit(cliOptions) if (initGit) { this.run(`git init`) setProjectGit(ctx, true) } const generator = new Generator({ ctx, name, cliOptions, answers: { appName, templateName } }) await generator.generate() try { let users = this.run(`users`, { stdio: 'pipe' }) users = users && users.toString() || '' if (users) { let user = users.split(' ')[0] user = user.replace(/\n/g, '') this.run(`chown -R ${user} ${ctx}`) } } catch (e) {} // generate done if (initGit) { this.run(`git add -A && git commit -m "${cliOptions.gitc || ':tada: Initialization. —— Powered by @lvl/wxapp-cli'}"`) } stopSpinner() log() log() log(chalk.cyan(`===================================`)) log() log(`小程序项目初始化完成,现在你可以:`) log() log(chalk.cyan(`$ cd ${name}`)) log(chalk.cyan(`$ wxapp-cli dev`)) log() log(`打开微信开发者工具,将项目目录指向 ${chalk.cyan(name + '/dist')}`) log() log(`初始化的配置,可在 ${chalk.cyan(name + '/wxapp-cli.config.js')} 文件中修改`) log() } run (cmd, ops) { return execSync(cmd, Object.assign({ cwd: this.ctx, stdio: 'ignore' }, ops || {})) } shouldInitGit (cliOptions) { if (!_hasGit) { return false } // --gitc if (cliOptions.forceGit) { return true } // --no-git if (cliOptions.git === false || cliOptions.git === 'false') { return false } // default: true unless already in a git repo return !hasProjectGit(this.ctx) } }