Taro init Demo

const inquirer = require('inquirer');
const chalk = require('chalk');

const DEFAULT_TEMPLATE_SRC = 'github:NervJS/taro-project-templates#v3.1'
const DEFAULT_TEMPLATE_SRC_GITEE = 'direct:https://gitee.com/o2team/taro-project-templates.git#v3.1'

const askProjectName = function (conf, prompts) {
    if ((typeof conf.projectName) !== 'string') {
        prompts.push({
            type: 'input',
            name: 'projectName',
            message: '请输入项目名称!',
            validate(input) {
                if (!input) {
                    return '项目名不能为空!'
                }
                if (fs.existsSync(input)) {
                    return '当前目录已经存在同名项目,请换一个项目名!'
                }
                return true
            }
        })
    } else if (fs.existsSync(conf.projectName)) {
        prompts.push({
            type: 'input',
            name: 'projectName',
            message: '当前目录已经存在同名项目,请换一个项目名!',
            validate(input) {
                if (!input) {
                    return '项目名不能为空!'
                }
                if (fs.existsSync(input)) {
                    return '项目名依然重复!'
                }
                return true
            }
        })
    }
}

const askTemplateSource = async function (conf, prompts) {
    let localTemplateSource = DEFAULT_TEMPLATE_SRC

    const choices = [
        {
            name: 'Gitee(最快)',
            value: DEFAULT_TEMPLATE_SRC_GITEE
        },
        {
            name: 'Github(最新)',
            value: DEFAULT_TEMPLATE_SRC
        }
    ]

    if (localTemplateSource && localTemplateSource !== DEFAULT_TEMPLATE_SRC && localTemplateSource !== DEFAULT_TEMPLATE_SRC_GITEE) {
        choices.unshift({
            name: `本地模板源:${localTemplateSource}`,
            value: localTemplateSource
        })
    }

    prompts.push({
        type: 'list',
        name: 'templateSource',
        message: '请选择模板源',
        choices
    })
}

async function ask() {
    let prompts = []
    const conf = {}
    askProjectName(conf, prompts)

    await askTemplateSource(conf, prompts)
    console.log(chalk.green('Taro 即将创建一个新项目!'))
    const answers = await inquirer.prompt(prompts)
    console.log("🚀 ~ file: addExper.js ~ line 87 ~ answers", answers)
};

ask()
posted @ 2022-02-24 15:12  远方的少年🐬  阅读(93)  评论(0编辑  收藏  举报