@ainc/script
Version:
Script compiler for typescript
160 lines (135 loc) • 3.72 kB
text/typescript
/**
*****************************************
* Created by edonet@163.com
* Created on 2021-04-11 12:17:19
*****************************************
*/
'use strict';
/**
*****************************************
* 加载依赖
*****************************************
*/
import { cwd } from '@ainc/fs/dist/cwd';
import { json } from '@ainc/fs/dist/json';
import { Parser } from './helpers/argv';
/**
*****************************************
* 选项
*****************************************
*/
const parser = new Parser({
project: {
type: 'array',
alias: 'p',
description: 'compile typescript project.',
},
eval: {
type: 'boolean',
alias: 'e',
description: 'eval source code.',
},
watch: {
type: 'boolean',
alias: 'w',
description: 'watch input files.',
},
exclude: {
type: 'array',
description: 'the exclude pattern for compile.',
},
version: {
type: 'boolean',
alias: 'v',
description: 'Print the command\'s version.',
},
help: {
type: 'boolean',
alias: 'h',
description: 'print this message.',
},
});
/**
*****************************************
* 定义命令
*****************************************
*/
export class Command {
/** 执行命令 */
public run(argv: string[]): void {
const opts = parser.parse(argv);
// 显示帮助信息
if (opts.help || !argv.length) {
return this.help();
}
// 显示版本信息
if (opts.version) {
return this.version();
}
// 编译项目
if (opts.project) {
const { compile } = require('./compiler') as typeof import('./compiler');
// 执行编译
return compile({
watch: opts.watch,
argv: opts.argv,
include: opts.project,
exclude: opts.exclude,
});
}
// 获取脚本输入
const input = opts.argv.find(key => key.charAt(0) !== '-');
// 执行文件
if (input) {
const { Script } = require('./script') as typeof import('./script');
const script = new Script();
// 打印结果
this.print(
opts.eval ? script.run(input) : script.execute(input)
);
// 监听文件
opts.watch && script.watch(this.print);
}
}
/** 打印帮助信息 */
public help(): void {
const path = cwd(__dirname, '../package.json');
const pkg: TypedRecord<string> = json(path) || {};
// 打印配置信息
parser.print({
name: 'esc',
usage: '[flags]',
version: pkg.version,
description: pkg.description,
});
}
/** 打印版本信息 */
public version(): void {
const path = cwd(__dirname, '../package.json');
const pkg = json(path) || {};
// 打印内容
console.log(`Version: ${pkg.version}`);
}
/** 执行脚本 */
public print(status?: unknown): void {
if (typeof status !== 'object' || (status && Object.keys(status).length)) {
console.log(status);
}
}
}
/**
*****************************************
* 以主模块启动
*****************************************
*/
if (module === require.main) {
run();
}
/**
*****************************************
* 执行命令
*****************************************
*/
export function run(argv = process.argv.slice(2)): void {
return new Command().run(argv);
}