init.js 2.42 KB
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const enquirer_1 = require("enquirer");
const utils = tslib_1.__importStar(require("../utils"));
const path_1 = tslib_1.__importDefault(require("path"));
const fs_1 = tslib_1.__importDefault(require("fs"));
const __1 = require("../");
const TYPE_TS = 'typescript';
const TYPE_JS = 'javascript';
class InitCommand {
    constructor() {
        this.description = 'Init egg-ts-helper in your existing project';
        this.options = '<type>';
    }
    async run(_, { args, cwd }) {
        let type = args[1];
        const pkgInfo = utils.getPkgInfo(cwd);
        const typeList = [TYPE_TS, TYPE_JS];
        pkgInfo.egg = pkgInfo.egg || {};
        // verify type
        if (!typeList.includes(type)) {
            const result = await enquirer_1.prompt({
                type: 'autocomplete',
                name: 'type',
                message: 'Choose the type of your project',
                choices: utils.checkMaybeIsJsProj(cwd) ? typeList.reverse() : typeList,
            }).catch(() => {
                utils.log('cancel initialization');
                return { type: '' };
            });
            type = result.type;
        }
        if (type === TYPE_JS) {
            // create jsconfig.json
            const result = utils.writeJsConfig(cwd);
            if (result) {
                utils.log('create ' + result);
            }
        }
        else if (type === TYPE_TS) {
            pkgInfo.egg.typescript = true;
            // create tsconfig.json
            const result = utils.writeTsConfig(cwd);
            if (result) {
                utils.log('create ' + result);
            }
        }
        else {
            return;
        }
        // add egg-ts-helper/register to egg.require
        pkgInfo.egg.require = pkgInfo.egg.require || [];
        if (!pkgInfo.egg.require.includes('egg-ts-helper/register') && !pkgInfo.egg.declarations) {
            pkgInfo.egg.declarations = true;
        }
        // write package.json
        const pkgDist = path_1.default.resolve(cwd, './package.json');
        fs_1.default.writeFileSync(pkgDist, JSON.stringify(pkgInfo, null, 2));
        utils.log('change ' + pkgDist);
        // build once
        utils.log('create d.ts ...');
        __1.createTsHelperInstance({ cwd }).build();
        utils.log('complete initialization');
    }
}
exports.default = new InitCommand();