Skip to content

Commit

Permalink
feat: 🎸 使用 ts 改写 cli
Browse files Browse the repository at this point in the history
  • Loading branch information
codexu committed Jun 30, 2021
1 parent 32baf28 commit 7a837aa
Show file tree
Hide file tree
Showing 15 changed files with 133 additions and 80 deletions.
Binary file modified .DS_Store
Binary file not shown.
9 changes: 8 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ module.exports = {
"es2021": true,
"node": true
},
"extends": "eslint:recommended",
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12
},
"plugins": [
"@typescript-eslint"
],
"rules": {
}
};
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.DS_Store
node_modules
/bin
/dist
package-lock.json

Expand Down
18 changes: 0 additions & 18 deletions bin/utils/hasDir.js

This file was deleted.

18 changes: 0 additions & 18 deletions bin/x-build.js

This file was deleted.

11 changes: 9 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
"x": "./bin/x-build.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"build": "rm -rf bin && tsc --build"
},
"repository": {
"type": "git",
Expand All @@ -27,6 +29,11 @@
"prettier": "^2.3.2"
},
"devDependencies": {
"eslint": "^7.29.0"
"@types/node": "^15.12.5",
"@typescript-eslint/eslint-plugin": "^4.28.1",
"@typescript-eslint/parser": "^4.28.1",
"eslint": "^7.29.0",
"ts-node-dev": "^1.1.6",
"typescript": "^4.3.4"
}
}
18 changes: 9 additions & 9 deletions bin/createTemplate.js → src/createTemplate.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const ejs = require("ejs");
const fs = require('fs-extra');
const path = require("path");
const prettier = require("prettier");
const options = require("./options");
import ejs = require("ejs");
import fs = require('fs-extra');
import path = require("path");
import prettier = require("prettier");
import options from "./options";

module.exports = (templatePath) => {
return async function (src) {
export default function (templatePath: string) {
return async function (src: string): Promise<void> {
const file = path.parse(src);
const readFilePath = path.resolve(templatePath, file.dir ,`${file.name}.ejs`);
const readFilePath = path.resolve(templatePath, file.dir, `${file.name}.ejs`);
const outputFilePath = path.resolve(templatePath, src);

const templateCode = await fs.readFile(readFilePath);
Expand All @@ -20,4 +20,4 @@ module.exports = (templatePath) => {
await fs.outputFile(outputFilePath, prettierCode)
await fs.remove(readFilePath)
}
};
}
36 changes: 17 additions & 19 deletions bin/creator.js → src/creator.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,50 @@
// 写入文件,安装依赖
const fs = require('fs-extra');
const chalk = require('chalk');
const path = require('path');
const {
spawn
} = require('child_process');
const clearConsole = require('./utils/clearConsole');

const CreateTemplate = require('./createTemplate')
import fs = require('fs-extra');
import chalk = require('chalk');
import path = require('path');
import { spawn } from 'child_process';
import clearConsole from './utils/clearConsole';
import createTemplate from './createTemplate';
import options from './options';

let startTime, endTime;

module.exports = async function (name) {
export default async function (name: string): Promise<void> {
// CLI 模板文件夹路径
const src = path.resolve(__dirname, '../template');
// 目标路径
const dest = path.resolve(process.cwd(), name);
const createTemplate = CreateTemplate(dest)
const writeTemplate = createTemplate(dest)

// startTime = new Date().getTime()
clearConsole('cyan', `X-BUILD v${require('../package').version}`);
clearConsole('cyan', `X-BUILD v${options.version}`);
console.log(`> 项目模板生成于目录: ${chalk.yellow(dest)}`);
// 拷贝模板文件
await fs.copy(src, dest);
await createTemplate('package.json');
await createTemplate('src/test.ts');
await writeTemplate('package.json');
await writeTemplate('src/test.ts');

await spawnCmd(dest, null, 'git', ['init'])
await spawnCmd(dest, null, 'git', ['add .'])
await spawnCmd(dest, null, 'git', ['commit -m "Initialize by X-BUILD"'])
console.log(`> 成功初始化 Git 仓库`);
console.log(`> 正在自动安装依赖,请稍等...`);
console.log('');
await spawnCmd(dest, 'inherit', 'npm', ['install']);
clearConsole('cyan', `Mapwhale v${require('../package').version}`);
await spawnCmd(dest, [0, 1, 2], 'npm', ['install']);
clearConsole('cyan', `Mapwhale v${options.version}`);
endTime = new Date().getTime();
const usageTime = (endTime - startTime) / 1000
console.log(`> 项目已经创建成功,用时${chalk.cyan(usageTime)}s,请输入以下命令继续...`);
console.log('');
console.log(chalk.cyan(' $ ') + chalk.blueBright(`cd ${name}`));
console.log(chalk.cyan(' $ ') + chalk.blueBright('npm run serve'));
};
}

/**
* 安装依赖指令
* @param {string} dest 需要执行指令的路径
*/
function spawnCmd(dest, stdio = 'inherit', cmd, instruction) {
function spawnCmd(dest: string, stdio = [0, 1, 2], cmd: string, instruction) {
const ls = spawn(cmd, instruction, {
cwd: dest,
stdio: stdio,
Expand All @@ -55,7 +53,7 @@ function spawnCmd(dest, stdio = 'inherit', cmd, instruction) {
return new Promise((resolve, reject) => {
ls.on('close', (code) => {
if (code === 0) {
resolve()
resolve(true)
} else {
reject();
}
Expand Down
3 changes: 2 additions & 1 deletion bin/options.js → src/options.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
export default {
name: '',
version: '',
components: {
elementPlus: false
}
Expand Down
4 changes: 4 additions & 0 deletions src/typings.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module '*.json' {
const value: JSON;
export default value;
}
17 changes: 5 additions & 12 deletions bin/utils/clearConsole.js → src/utils/clearConsole.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
const chalk = require('chalk');
const readline = require('readline');
import chalk = require('chalk');
import readline = require('readline');
import options from '../options';

/**
* 控制台清空,并输出提示信息
* @param {String} 输出信息颜色
* @param {String} 输出信息
*/

function clearConsole(color, str) {
export default function (color: string, str: string):void {
if (process.stdout.isTTY) {
console.log('');
const cutLine = ` x-build ${require('../../package.json').version} `;
const cutLine = ` x-build ${options.version} `;
console.log(chalk.bgCyan(' -'.repeat((process.stdout.columns - cutLine.length) / 4) + cutLine + '- '.repeat((process.stdout.columns - cutLine.length) / 4)));
const blank = '\n'.repeat(process.stdout.rows);
console.log(blank);
Expand All @@ -20,5 +15,3 @@ function clearConsole(color, str) {
console.log('');
}
}

module.exports = clearConsole;
17 changes: 17 additions & 0 deletions src/utils/hasDir.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import fs = require('fs');
import chalk = require('chalk');

export default function(name: string): Promise<boolean> {
return new Promise ((resolve) => {
fs.access(name, error => {
if (error) {
console.log(chalk.red(
`The ${name} folder already exists in the current directory. Please try to use another project name!`
));
process.exit(1);
} else {
resolve(true);
}
});
});
}
11 changes: 11 additions & 0 deletions src/utils/packageVersion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import fs = require('fs-extra');
import path = require("path");
import options from "../options";

export default async function (): Promise<void> {
const packageFile = path.resolve(__dirname, '../../package.json');

const packageCode = await fs.readFile(packageFile);
const packageJson = JSON.parse(packageCode.toString())
options.version = packageJson.version;
}
24 changes: 24 additions & 0 deletions src/x-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#! /usr/bin/env node

import program = require('commander');
import hasDir from './utils/hasDir';
import creator from './creator';
import packageVersion from './utils/packageVersion';
import options from './options';

async function run() {
await packageVersion();
program.version(options.version)
.usage('<command> [options]');

program.command('create <app-name>')
.description('create a new project with vue3 + typescript by x-build')
.action(async (name) => {
await hasDir(name);
creator(name);
});

program.parse(process.argv);
}

run();
26 changes: 26 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"compileOnSave": true,
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"inlineSourceMap":true,
"noImplicitThis": true,
"noUnusedLocals": true,
"stripInternal": true,
"pretty": true,
"declaration": true,
"outDir": "bin",
"baseUrl": "./",
"paths": {
"*": ["src/*"]
}
},
"exclude": [
"bin",
"documents",
"template",
]
}

0 comments on commit 7a837aa

Please sign in to comment.