├── ._npmignore ├── .gitignore ├── README.md ├── bin └── uniapp ├── cover.png ├── package.json ├── scripts ├── deploy.sh └── npm-link.sh ├── src ├── cli.ts ├── commands │ ├── default.ts │ ├── init.ts │ ├── list.ts │ ├── update.ts │ └── version.ts ├── constants.ts └── util │ ├── exec.ts │ ├── format.ts │ ├── fs.ts │ ├── index.ts │ ├── install-npm-packages.ts │ └── tsc │ ├── helper.ts │ ├── index.ts │ ├── transform-path-mapping.ts │ └── types.ts ├── tsconfig.json ├── tslint.json └── typings └── extends └── cli-spinner └── cli-spinner.d.ts /._npmignore: -------------------------------------------------------------------------------- 1 | # base dir /dist/ 2 | 3 | /test/ 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | dist 4 | typings/* 5 | !typings/extends/ 6 | uniapp-conf.json 7 | demo/ 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 一套用于 WEB APP 开发 和 Mobile APP 开发的解决方案 2 | 3 | ### 安装 4 | 5 | ``` 6 | npm install uniapp-cli -g 7 | ``` 8 | --- 9 | 10 | 11 | ### 使用 12 | 13 | 在本地终端进入项目位置 然后使用 ```uniapp init``` 命令 选择需要应用的框架程序, 14 | 更多的的命令使用帮助可以使用 ```uniapp --help``` 命令 获取更多帮助信息 15 | 16 | ![uniapp -help](./cover.png?2) -------------------------------------------------------------------------------- /bin/uniapp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | var Shim = require('clime').Shim; 3 | var cli = require('../cli.js').default; 4 | new Shim(cli).execute(process.argv); -------------------------------------------------------------------------------- /cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maolion/uniapp-cli/ca2c862fef1a62be5f1a6daf6b23fbf16a04bc69/cover.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "uniapp-cli", 3 | "version": "0.1.0-dev.4", 4 | "description": "一套用于 WEB APP 开发 和 Mobile APP 开发的解决方案", 5 | "main": "./cli.js", 6 | "typings": "./cli.d.ts", 7 | "scripts": { 8 | "start": "tsc --watch", 9 | "tslint": "tslint", 10 | "lint": "tslint --project tsconfig.json --type-check -c tslint.json", 11 | "build": "npm run lint && tsc --declaration", 12 | "link": "npm run build && ./scripts/npm-link.sh", 13 | "unlink": "cd dist && npm unlink", 14 | "deploy": "./scripts/deploy.sh", 15 | "prepublishOnly": "exit 1", 16 | "test": "echo \"Error: no test specified\" && exit 1" 17 | }, 18 | "bin": { 19 | "uniapp": "./bin/uniapp" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/maolion/uniapp-cli.git" 24 | }, 25 | "keywords": [ 26 | "uniapp", 27 | "uniapp-cli", 28 | "spa", 29 | "react", 30 | "react native", 31 | "web", 32 | "webpack" 33 | ], 34 | "author": "maolion.j@gmail.com", 35 | "license": "MIT", 36 | "bugs": { 37 | "url": "https://github.com/maolion/uniapp-cli/issues" 38 | }, 39 | "homepage": "https://github.com/maolion/uniapp-cli#readme", 40 | "peerDependencies": { 41 | "typescript": ">=2.3.0-dev" 42 | }, 43 | "devDependencies": { 44 | "@types/chalk": "^0.4.31", 45 | "@types/fs-extra": "^2.0.0", 46 | "@types/inquirer": "0.0.32", 47 | "@types/node": "^7.0.12", 48 | "tslint": "^5.0.0", 49 | "typescript": "^2.3.0-dev.20170407", 50 | "vts": "^5.0.1" 51 | }, 52 | "dependencies": { 53 | "chalk": "^1.1.3", 54 | "cli-spinner": "^0.2.6", 55 | "clime": "^0.5.0-dev.3", 56 | "fs-extra": "^2.1.2", 57 | "inquirer": "^3.0.6", 58 | "source-map-support": "^0.4.14", 59 | "villa": "^0.2.11" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo "deploying ..." 4 | 5 | echo "cleaning previouse build files ..." 6 | rm -rf ./dist 7 | 8 | echo "building ..." 9 | npm run build || exit 0 10 | 11 | echo "copying ..." 12 | 13 | cp ./uniapp-conf.json ./dist/uniapp-conf.json 14 | cp ./package.json ./dist/package.json 15 | cp ./._npmignore ./dist/.npmignor 16 | cp -r ./bin ./dist/bin 17 | 18 | perl -pi -w -e 's/"prepublishOnly": "exit 1"/"prepublishOnly": ""/g;' ./dist/package.json 19 | 20 | cd ./dist 21 | 22 | echo "publishing ..." 23 | 24 | if ! [ -z "$1" ] 25 | then 26 | npm publish --tag $1 27 | else 28 | npm publish 29 | fi 30 | -------------------------------------------------------------------------------- /scripts/npm-link.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo "npm linking ..." 4 | 5 | cp -fr ./bin/ ./dist/bin/ 6 | cp -f ./uniapp-conf.json ./dist 7 | cp -f ./package.json ./dist 8 | 9 | perl -pi -w -e 's/"prepublishOnly": "exit 1"/"prepublishOnly": ""/g;' ./dist/package.json 10 | 11 | cd ./dist 12 | npm link 13 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | 3 | import { CLI, Shim } from 'clime'; 4 | import * as FS from 'fs'; 5 | import * as Path from 'path'; 6 | 7 | import { 8 | CWD, 9 | LOCAL_NODE_MODULES, 10 | LOCAL_UNIAPP_CONF_PATH, 11 | UNIAPP_COMMANDS_ROOT, 12 | UNIAPP_CONF_PATH 13 | } from './constants'; 14 | 15 | let roots = [ 16 | { 17 | label: 'SUBCOMMANDS', 18 | path: UNIAPP_COMMANDS_ROOT 19 | } 20 | ]; 21 | 22 | if (FS.existsSync(LOCAL_UNIAPP_CONF_PATH)) { 23 | let uniappConf = require(LOCAL_UNIAPP_CONF_PATH); 24 | let extendCommandsDir = uniappConf.framework && Path.join(LOCAL_NODE_MODULES, uniappConf.framework, 'commands'); 25 | 26 | if (extendCommandsDir && FS.existsSync(extendCommandsDir)) { 27 | roots.push({ 28 | label: `EXTEND SUBCOMMANDS - for based ${uniappConf.framework} framework project`, 29 | path: extendCommandsDir 30 | }); 31 | } 32 | } 33 | 34 | let cli = new CLI('uniapp', roots); 35 | 36 | export default cli; 37 | -------------------------------------------------------------------------------- /src/commands/default.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Command, 3 | HelpInfo, 4 | Printable, 5 | UsageError, 6 | command, 7 | param 8 | } from 'clime'; 9 | 10 | import * as Chalk from 'chalk'; 11 | import cli from '../cli'; 12 | 13 | export const description = Chalk.grey(`\ 14 | \n 15 | ▄ ▄ ▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ 16 | ▐░▌ ▐░▌▐░░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ 17 | ▐░▌ ▐░▌▐░▌░▌ ▐░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ 18 | ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ 19 | ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ 20 | ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ 21 | ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ 22 | ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ 23 | ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▌▐░▌ ▐░▌ 24 | ▐░░░░░░░░░░░▌▐░▌ ▐░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌ 25 | ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ 26 | `); 27 | 28 | export const subcommands = [ 29 | { 30 | name: 'init', 31 | brief: 'Create and initialize a new project' 32 | }, 33 | { 34 | name: 'update', 35 | alias: 'up', 36 | brief: 'Upgrade the framework' 37 | }, 38 | { 39 | name: 'list', 40 | alias: 'ls', 41 | brief: 'Output list of supported frameworks' 42 | }, 43 | { 44 | name: 'version', 45 | alias: 'v', 46 | brief: 'Output uniapp/frameworks version' 47 | } 48 | ]; 49 | 50 | /* 51 | ┌────────────────────────────────────────────┐ 52 | │ Update available: 1.11.0 (current: 1.10.2) │ 53 | │ Run npm install -g uniapp-cli to update. │ 54 | └────────────────────────────────────────────┘ 55 | */ 56 | -------------------------------------------------------------------------------- /src/commands/init.ts: -------------------------------------------------------------------------------- 1 | import * as FS from 'fs-extra'; 2 | import * as Path from 'path'; 3 | 4 | import * as Chalk from 'chalk'; 5 | import { Spinner } from 'cli-spinner'; 6 | import { 7 | Command, 8 | command, 9 | param, 10 | } from 'clime'; 11 | import * as Inquirer from 'inquirer'; 12 | import * as Villa from 'villa'; 13 | 14 | import { 15 | exec, 16 | installPackagesFromNPM, 17 | safeStat 18 | } from '../util'; 19 | 20 | import { 21 | CWD, 22 | LOCAL_UNIAPP_CONF_PATH, 23 | UNIAPP_CONF_PATH 24 | } from '../constants'; 25 | 26 | interface FormResult { 27 | name: string; 28 | framework: string; 29 | description: string; 30 | author: string; 31 | } 32 | 33 | export interface FrameworkInfo { 34 | name: string; 35 | description: string; 36 | } 37 | 38 | @command({ 39 | brief: 'Create and initialize a new project' 40 | }) 41 | export default class InitCommand extends Command { 42 | async execute( 43 | @param({ 44 | required: true, 45 | type: String, 46 | description: 'project name' 47 | }) 48 | projectName: string 49 | ) { 50 | let projectPath = Path.resolve(CWD, projectName); 51 | 52 | if (await safeStat(projectPath)) { 53 | throw new Error(`Directory '${projectName}' already exists.`); 54 | } 55 | 56 | let form = await InitCommand._fillingForm(); 57 | form.name = projectName; 58 | 59 | try { 60 | await this._init(projectPath, form); 61 | } catch (e) { 62 | await Villa.call(FS.remove, projectPath); 63 | throw e; 64 | } 65 | } 66 | 67 | private async _init(projectPath: string, form: FormResult) { 68 | let spinner = new Spinner('Installing project...'); 69 | spinner.setSpinnerString('|/-\\'); 70 | spinner.start(); 71 | 72 | try { 73 | console.log(`Creating a new ${Chalk.bold(form.framework)} project in ${Chalk.bold(projectPath)}`); 74 | 75 | await Villa.call(FS.ensureDir, projectPath); 76 | await Villa.call(FS.writeFile, 77 | Path.join(projectPath, 'package.json'), 78 | InitCommand._generatorPackageConfigContent(form) 79 | ); 80 | await Villa.call(FS.writeFile, 81 | Path.join(projectPath, 'uniapp-conf.json'), 82 | InitCommand._generatorUniappConfigContent(form) 83 | ); 84 | await installPackagesFromNPM(projectPath, [ 85 | 'uniapp@latest', 86 | `${form.framework}@latest`, 87 | 'react@latest', 88 | ]); 89 | 90 | } catch (e) { 91 | throw e; 92 | } finally { 93 | spinner.stop(true); 94 | } 95 | 96 | console.log(Chalk.green('\n=^_^= Initialization is complete!')); 97 | 98 | } 99 | 100 | private static async _fillingForm(): Promise { 101 | let frameworks = InitCommand._getSupportedFrameworks(); 102 | 103 | return await Inquirer.prompt([ 104 | { 105 | type: 'list', 106 | name: 'framework', 107 | message: 'Choice a framework for your project', 108 | choices: frameworks.map((framework: any) => { 109 | return { 110 | value: framework.name, 111 | name: `${Chalk.bold(framework.name)} - ${framework.description}` 112 | }; 113 | }) 114 | }, 115 | { 116 | type: 'input', 117 | name: 'description', 118 | message: 'description:' 119 | }, 120 | { 121 | type: 'input', 122 | name: 'author', 123 | message: 'author:' 124 | } 125 | ]) as any; 126 | } 127 | 128 | private static _getSupportedFrameworks(): FrameworkInfo[] { 129 | let uniappConf = require(UNIAPP_CONF_PATH); 130 | return uniappConf.frameworks || []; 131 | } 132 | 133 | private static _generatorPackageConfigContent(form: FormResult) { 134 | let packageConfig = { 135 | name: form.name, 136 | version: '0.0.1', 137 | description: '', 138 | repository: '', 139 | license: '', 140 | main: '', 141 | scripts: {}, 142 | author: form.author, 143 | dependencies: {}, 144 | devDependencies: {} 145 | }; 146 | 147 | return JSON.stringify(packageConfig, undefined, ' '); 148 | } 149 | 150 | private static _generatorUniappConfigContent(form: FormResult) { 151 | let uniappConfig = { 152 | framework: form.framework 153 | }; 154 | 155 | return JSON.stringify(uniappConfig, undefined, ' '); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/commands/list.ts: -------------------------------------------------------------------------------- 1 | import * as Chalk from 'chalk'; 2 | import { 3 | Command, 4 | command, 5 | metadata 6 | } from 'clime'; 7 | 8 | import { 9 | TableCaption, 10 | TableRow, 11 | buildTableOutput 12 | } from '../util/format'; 13 | 14 | import { UNIAPP_CONF_PATH } from '../constants'; 15 | 16 | @command({ 17 | brief: 'Output list of supported frameworks' 18 | }) 19 | export default class extends Command { 20 | @metadata 21 | execute() { 22 | let uniappConf = require(UNIAPP_CONF_PATH); 23 | let tableRows: TableRow[] = []; 24 | 25 | tableRows.push(new TableCaption( 26 | Chalk.green('list of supported frameworks') 27 | )); 28 | 29 | for (let frameworkInfo of uniappConf.frameworks || []) { 30 | tableRows.push([ 31 | Chalk.bold(frameworkInfo.name), 32 | frameworkInfo.description 33 | ]); 34 | } 35 | 36 | return buildTableOutput(tableRows, { indent: 2, spaces: ' - ' }); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/commands/update.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maolion/uniapp-cli/ca2c862fef1a62be5f1a6daf6b23fbf16a04bc69/src/commands/update.ts -------------------------------------------------------------------------------- /src/commands/version.ts: -------------------------------------------------------------------------------- 1 | import * as Path from 'path'; 2 | 3 | import { 4 | Command, 5 | command, 6 | metadata 7 | } from 'clime'; 8 | 9 | import { UNIAPP_DIR } from '../constants'; 10 | 11 | @command({ 12 | brief: 'Output uniapp/frameworks version' 13 | }) 14 | export default class extends Command { 15 | @metadata 16 | execute() { 17 | return require(Path.join(UNIAPP_DIR, 'package.json')).version; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | import * as Path from 'path'; 2 | 3 | export const CWD = process.cwd(); 4 | export const UNIAPP_DIR = Path.resolve(__dirname, '../'); 5 | export const NODE_MODULES = Path.join(UNIAPP_DIR, 'node_modules'); 6 | export const UNIAPP_CONF_PATH = Path.join(UNIAPP_DIR, 'uniapp-conf.json'); 7 | export const UNIAPP_COMMANDS_ROOT = Path.join(UNIAPP_DIR, 'dist/commands'); 8 | 9 | export const LOCAL_UNIAPP_CONF_PATH = Path.join(CWD, 'uniapp-conf.json'); 10 | export const LOCAL_NODE_MODULES = Path.join(CWD, 'node_modules'); 11 | -------------------------------------------------------------------------------- /src/util/exec.ts: -------------------------------------------------------------------------------- 1 | import * as ChildProcess from 'child_process'; 2 | 3 | export type WriteHandler = (data: string) => any; 4 | 5 | export interface ExecuteOptions { 6 | log?: WriteHandler; 7 | errLog?: WriteHandler; 8 | args?: string[]; 9 | cwd?: string; 10 | catchOutput?: boolean; 11 | } 12 | 13 | export function exec(execute: string, options: ExecuteOptions = {}) { 14 | let log = options.log; 15 | let errLog = options.errLog; 16 | let cache = ''; 17 | 18 | return new Promise((resolve, reject) => { 19 | let instance = ChildProcess.exec( 20 | execute + (options.args ? ' ' + options.args.join(' ') : ''), 21 | { 22 | cwd: options.cwd || process.cwd() 23 | }, 24 | err => { 25 | 26 | } 27 | ); 28 | 29 | instance.stdout.on('data', (data: Buffer) => { 30 | let dataContent = data.toString('utf8'); 31 | 32 | if (options.catchOutput) { 33 | cache += dataContent; 34 | } 35 | 36 | if (log) { 37 | log(dataContent); 38 | } 39 | }); 40 | 41 | if (errLog) { 42 | instance.stderr.on('data', (data: Buffer) => { 43 | if (errLog) { 44 | errLog(data.toString('utf8')); 45 | } 46 | }); 47 | } 48 | 49 | instance.on('exit', (code: number, signal: any) => { 50 | if (code !== 0) { 51 | reject(code); 52 | return; 53 | } 54 | 55 | resolve({ code, output: cache }); 56 | }); 57 | }); 58 | } 59 | -------------------------------------------------------------------------------- /src/util/format.ts: -------------------------------------------------------------------------------- 1 | import * as Chalk from 'chalk'; 2 | 3 | export class TableCaption { 4 | constructor(public text: string) { } 5 | } 6 | 7 | export type TableRow = TableCaption | (string | undefined)[]; 8 | 9 | export function buildTableOutput(rows: TableRow[], { 10 | spaces = 4 as string | number, 11 | indent = 0 as string | number 12 | } = {}): string { 13 | let maxTextLengths: number[] = []; 14 | 15 | for (let row of rows) { 16 | let lastNoneEmptyIndex = 0; 17 | if (row instanceof TableCaption) { 18 | continue; 19 | } 20 | 21 | for (let i = 0; i < row.length; i++) { 22 | let text = row[i] || ''; 23 | let textLength = Chalk.stripColor(text).length; 24 | 25 | if (!textLength) { 26 | continue; 27 | } 28 | 29 | lastNoneEmptyIndex = i; 30 | 31 | if (maxTextLengths.length > i) { 32 | maxTextLengths[i] = Math.max(maxTextLengths[i], textLength); 33 | } else { 34 | maxTextLengths[i] = textLength; 35 | } 36 | } 37 | 38 | row.splice(lastNoneEmptyIndex + 1); 39 | } 40 | 41 | let indentStr = typeof indent === 'string' ? 42 | indent : 43 | new Array(indent + 1).join(' '); 44 | 45 | return rows 46 | .map(row => { 47 | 48 | if (row instanceof TableCaption) { 49 | return row.text + '\n'; 50 | } 51 | 52 | let line = indentStr; 53 | 54 | for (let i = 0; i < row.length; i++) { 55 | let text = row[i] || ''; 56 | let textLength = Chalk.stripColor(text).length; 57 | 58 | let maxLength = maxTextLengths[i]; 59 | 60 | line += text; 61 | line += new Array(maxLength - textLength + 1).join(' '); 62 | 63 | if (i < row.length - 1) { 64 | if (typeof spaces === 'string') { 65 | line += spaces; 66 | } else { 67 | line += new Array(spaces + 1).join(' '); 68 | } 69 | } 70 | } 71 | 72 | return line; 73 | }) 74 | .join('\n') + '\n'; 75 | } 76 | 77 | export function indent(text: string, indent: string | number = 2): string { 78 | let indentStr = typeof indent === 'string' ? 79 | indent.replace(/\r/g, '') : 80 | Array(indent + 1).join(' '); 81 | 82 | return text.replace(/^/mg, indentStr); 83 | } 84 | -------------------------------------------------------------------------------- /src/util/fs.ts: -------------------------------------------------------------------------------- 1 | import * as FS from 'fs'; 2 | import * as Path from 'path'; 3 | 4 | import * as v from 'villa'; 5 | 6 | export async function safeStat(path: string): Promise { 7 | return await v.call(FS.stat, path).catch(v.bear); 8 | } 9 | 10 | export async function existsFile(path: string): Promise { 11 | let stats = await safeStat(path); 12 | return !!stats && stats.isFile(); 13 | } 14 | 15 | export async function existsDir(path: string): Promise { 16 | let stats = await safeStat(path); 17 | return !!stats && stats.isDirectory(); 18 | } 19 | 20 | export function joinPaths(roots: string[], relPath: string): string[] { 21 | return roots.map(root => Path.join(root, relPath)); 22 | } 23 | 24 | export type PathType = 'file' | 'dir'; 25 | 26 | export async function findPaths(type: PathType, roots: string[], relPath?: string): Promise { 27 | let paths = relPath ? joinPaths(roots, relPath) : roots; 28 | 29 | paths = await v.filter(paths, async path => { 30 | let stats = await safeStat(path); 31 | 32 | if (!stats) { 33 | return false; 34 | } 35 | 36 | switch (type) { 37 | case 'file': 38 | return stats.isFile(); 39 | case 'dir': 40 | return stats.isDirectory(); 41 | } 42 | }); 43 | 44 | return paths.length ? paths : undefined; 45 | } 46 | 47 | export function readFile(fileName: string, encoding?: string) { 48 | return FS.readFileSync(fileName, encoding).toString('utf8'); 49 | } 50 | -------------------------------------------------------------------------------- /src/util/index.ts: -------------------------------------------------------------------------------- 1 | export * from './exec'; 2 | export * from './install-npm-packages'; 3 | export * from './fs'; 4 | -------------------------------------------------------------------------------- /src/util/install-npm-packages.ts: -------------------------------------------------------------------------------- 1 | import * as Chalk from 'chalk'; 2 | import { exec } from './exec'; 3 | 4 | const DEPEND_TYPE_MAPPING: { [key: string]: string } = { 5 | normal: '--save', 6 | dev: '--save-dev', 7 | none: '' 8 | }; 9 | 10 | export function installPackagesFromNPM( 11 | cwd: string, packages: string[], dependType: string = 'normal', showLog = false) { 12 | 13 | let putedNewLine = false; 14 | return exec('npm install', { 15 | cwd, 16 | args: [packages.join(' '), DEPEND_TYPE_MAPPING[dependType] || ''], 17 | log: data => { 18 | if (!putedNewLine) { 19 | process.stdout.write('\n'); 20 | putedNewLine = true; 21 | } 22 | 23 | if (showLog) { 24 | process.stdout.write(data); 25 | } 26 | }, 27 | errLog: data => { 28 | if (!putedNewLine) { 29 | process.stdout.write('\n'); 30 | putedNewLine = true; 31 | } 32 | 33 | if (data.indexOf('npm ERR! ') > -1) { 34 | return process.stdout.write(Chalk.red(data)); 35 | } else { 36 | return process.stdout.write(Chalk.yellow(data)); 37 | } 38 | } 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /src/util/tsc/helper.ts: -------------------------------------------------------------------------------- 1 | import * as Path from 'path'; 2 | 3 | import { 4 | CompilerOptions, 5 | EmitFlags, 6 | ModuleKind, 7 | ScriptTarget, 8 | SyntaxKind 9 | } from 'typescript'; 10 | 11 | import { 12 | Identifier, 13 | Node, 14 | TransformFlags 15 | } from './types'; 16 | 17 | const supportedTypeScriptExtensions = ['.ts', '.tsx', '.d.ts']; 18 | 19 | export function isIdentifier(node: Node): node is Identifier { 20 | return node.kind === SyntaxKind.Identifier; 21 | } 22 | 23 | export function getEmitScriptTarget(compilerOptions: CompilerOptions) { 24 | return compilerOptions.target || ScriptTarget.ES3; 25 | } 26 | 27 | export function getEmitModuleKind(compilerOptions: CompilerOptions) { 28 | return typeof compilerOptions.module === 'number' ? 29 | compilerOptions.module : ( 30 | getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? 31 | ModuleKind.ES2015 : 32 | ModuleKind.CommonJS 33 | ); 34 | } 35 | 36 | export function getRelativePath(from: string, to: string) { 37 | let path = Path.relative(from, to); 38 | if (path && path.charAt(0) !== '.') { 39 | path = './' + path; 40 | } 41 | 42 | return path; 43 | } 44 | 45 | export function contains(array: T[], value: T): boolean { 46 | if (array) { 47 | for (const v of array) { 48 | if (v === value) { 49 | return true; 50 | } 51 | } 52 | } 53 | return false; 54 | } 55 | 56 | export function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean { 57 | if (!array1 || !array2) { 58 | return false; 59 | } 60 | 61 | if (array1.length !== array2.length) { 62 | return false; 63 | } 64 | 65 | for (let i = 0, l = array1.length; i < l; i++) { 66 | let a = array1[i]; 67 | let b = array2[i]; 68 | 69 | if (!(equaler ? equaler(a, b) : a === b)) { 70 | return false; 71 | } 72 | } 73 | 74 | return true; 75 | } 76 | 77 | export function isSupportedSourceFileName(fileName: string) { 78 | if (!fileName) { 79 | return false; 80 | } 81 | 82 | let fileNameStrLen = fileName.length; 83 | 84 | for (let extension of supportedTypeScriptExtensions) { 85 | if (fileNameStrLen > extension.length && fileName.endsWith(extension)) { 86 | return true; 87 | } 88 | } 89 | 90 | return false; 91 | } 92 | 93 | export function padLeft(s: string, length: number) { 94 | while (s.length < length) { 95 | s = ' ' + s; 96 | } 97 | return s; 98 | } 99 | 100 | export function padRight(s: string, length: number) { 101 | while (s.length < length) { 102 | s = s + ' '; 103 | } 104 | 105 | return s; 106 | } 107 | -------------------------------------------------------------------------------- /src/util/tsc/index.ts: -------------------------------------------------------------------------------- 1 | import * as Chalk from 'chalk'; 2 | import * as FS from 'fs-extra'; 3 | import * as Path from 'path'; 4 | 5 | import { 6 | CompilerHost, 7 | CompilerOptions, 8 | Diagnostic, 9 | DiagnosticCategory, 10 | ExitStatus, 11 | FileWatcher, 12 | FormatDiagnosticsHost, 13 | Node, 14 | ParsedCommandLine, 15 | Program, 16 | ScriptTarget, 17 | SourceFile as _SourceFile, 18 | createCompilerHost, 19 | createProgram, 20 | flattenDiagnosticMessageText, 21 | formatDiagnostics, 22 | getLineAndCharacterOfPosition, 23 | getPositionOfLineAndCharacter, 24 | parseConfigFileTextToJson, 25 | parseJsonConfigFileContent, 26 | sys 27 | } from 'typescript'; 28 | 29 | import { readFile } from '../fs'; 30 | 31 | import { 32 | arrayIsEqualTo, 33 | contains, 34 | getRelativePath, 35 | isSupportedSourceFileName, 36 | padLeft, 37 | padRight 38 | } from './helper'; 39 | 40 | import transformPathMapping from './transform-path-mapping'; 41 | 42 | const NL = sys.newLine; 43 | 44 | const supportedTypeScriptExtensions = ['.ts', '.tsx', '.d.ts']; 45 | 46 | interface Statistic { 47 | name: string; 48 | value: string; 49 | } 50 | 51 | export interface TSCOptions { 52 | watch?: boolean; 53 | cwd?: string; 54 | } 55 | 56 | export interface SourceFile extends _SourceFile { 57 | fileWatcher?: FileWatcher; 58 | } 59 | 60 | type ErrorHandler = (message: string) => void; 61 | 62 | const redForegroundEscapeSequence = '\u001b[91m'; 63 | const yellowForegroundEscapeSequence = '\u001b[93m'; 64 | const blueForegroundEscapeSequence = '\u001b[93m'; 65 | const gutterStyleSequence = '\u001b[100;30m'; 66 | const gutterSeparator = ' '; 67 | const resetEscapeSequence = '\u001b[0m'; 68 | const ellipsis = '...'; 69 | 70 | /** 自定义 tsc, 主要用于完成 path mapping 路径映射到实际的关联文件模块需求 */ 71 | export default function tsc(configFileName: string, options: TSCOptions = {}) { 72 | const watchSet = !!options.watch; 73 | const cwd = options.cwd || sys.getCurrentDirectory(); 74 | const defaultFormatDiagnosticsHost: FormatDiagnosticsHost = { 75 | getCurrentDirectory: () => sys.getCurrentDirectory(), 76 | getNewLine: () => sys.newLine, 77 | getCanonicalFileName: ( 78 | sys.useCaseSensitiveFileNames ? 79 | (fileName => fileName) : 80 | (fileName => fileName.toLowerCase()) 81 | ) 82 | }; 83 | 84 | let cachedConfigFileText: string | undefined; 85 | let compilerOptions: CompilerOptions; 86 | let configFileWatcher: FileWatcher; 87 | let directoryWatcher: FileWatcher; 88 | let cachedProgram: Program | undefined; 89 | let compilerHost: CompilerHost; 90 | let hostGetSourceFile: typeof compilerHost.getSourceFile; 91 | let timerHandleForRecompilation: any; 92 | let timerHandleForDirectoryChanges: any; 93 | let rootFileNames: string[]; 94 | 95 | let cachedExistingFiles: Map; 96 | let hostFileExists: typeof compilerHost.fileExists; 97 | let reportDiagnosticWorker = reportDiagnosticSimply; 98 | 99 | configFileName = Path.resolve(cwd, configFileName); 100 | 101 | // 监听 tsconfig.json 和 对应目录ts项目源代码目录的文件变动情况 102 | // 监听文件变通主要是触发实时编译的需求 103 | if (watchSet) { 104 | if (sys.watchFile) { 105 | configFileWatcher = sys.watchFile(configFileName, configFileChanged); 106 | } 107 | 108 | if (sys.watchDirectory) { 109 | directoryWatcher = sys.watchDirectory( 110 | Path.dirname(configFileName), 111 | watchedDirectoryChanged, 112 | true 113 | ); 114 | } 115 | } 116 | 117 | performCompilation(); 118 | 119 | function parseConfigFile() { 120 | 121 | if (!cachedConfigFileText) { 122 | try { 123 | cachedConfigFileText = readFile(configFileName); 124 | } catch (e) { 125 | reportWatchDiagnostic({ 126 | messageText: `Can not read file ${configFileName}: ${e.message}.` 127 | } as Diagnostic); 128 | 129 | sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); 130 | } 131 | } 132 | 133 | if (!cachedConfigFileText) { 134 | reportWatchDiagnostic({ 135 | messageText: `File ${configFileName} not found.` 136 | } as Diagnostic); 137 | 138 | sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); 139 | return; 140 | } 141 | 142 | // 解析 项目配置文件, 修正编译参数配置,搜索所有编译目标文件 143 | 144 | const result = parseConfigFileTextToJson(configFileName, cachedConfigFileText); 145 | const configObject = result.config; 146 | if (!configObject) { 147 | if (result.error) { 148 | reportDiagnostics([result.error]); 149 | } 150 | 151 | sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); 152 | return; 153 | } 154 | 155 | const configParseResult = parseJsonConfigFileContent( 156 | configObject, 157 | sys, 158 | Path.dirname(configFileName) 159 | ); 160 | 161 | if (configParseResult.errors.length > 0) { 162 | reportDiagnostics(configParseResult.errors); 163 | sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); 164 | } 165 | 166 | return configParseResult; 167 | } 168 | 169 | function performCompilation() { 170 | 171 | if (!cachedProgram) { 172 | const configParseResult = (parseConfigFile() as ParsedCommandLine); 173 | rootFileNames = configParseResult.fileNames; 174 | compilerOptions = configParseResult.options; 175 | 176 | compilerHost = createCompilerHost(compilerOptions); 177 | hostGetSourceFile = compilerHost.getSourceFile; 178 | compilerHost.getSourceFile = getSourceFile; 179 | 180 | hostFileExists = compilerHost.fileExists; 181 | compilerHost.fileExists = cachedFileExists; 182 | } 183 | 184 | if (compilerOptions.pretty) { 185 | reportDiagnosticWorker = reportDiagnosticPretty; 186 | } 187 | 188 | cachedExistingFiles = new Map(); 189 | 190 | const compileResult = compile(rootFileNames, compilerOptions, compilerHost); 191 | 192 | if (!watchSet) { 193 | return sys.exit(compileResult.exitStatus); 194 | } 195 | 196 | setCachedProgram(compileResult.program); 197 | 198 | reportWatchDiagnostic({ 199 | messageText: 'Compilation complete. Watching for file changes.' 200 | } as Diagnostic); 201 | } 202 | 203 | function cachedFileExists(fileName: string): boolean { 204 | let fileExists = cachedExistingFiles.get(fileName); 205 | 206 | if (fileExists === undefined) { 207 | cachedExistingFiles.set(fileName, fileExists = hostFileExists(fileName)); 208 | } 209 | 210 | return fileExists; 211 | } 212 | 213 | function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: ErrorHandler): SourceFile { 214 | if (cachedProgram) { 215 | const sourceFile = cachedProgram.getSourceFile(fileName) as SourceFile; 216 | 217 | // 使用已被处理过的文件缓存数据 218 | if (sourceFile && sourceFile.fileWatcher) { 219 | return sourceFile; 220 | } 221 | } 222 | 223 | const sourceFile = hostGetSourceFile(fileName, languageVersion, onError) as SourceFile; 224 | 225 | if (sourceFile && watchSet && sys.watchFile) { 226 | sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (_fileName: string, removed?: boolean) => { 227 | sourceFileChanged(sourceFile, removed); 228 | }); 229 | } 230 | 231 | return sourceFile; 232 | } 233 | 234 | function setCachedProgram(program: Program | undefined) { 235 | const newSourceFiles = program ? program.getSourceFiles() : undefined; 236 | 237 | if (cachedProgram && newSourceFiles) { 238 | const sourceFiles = cachedProgram.getSourceFiles() as SourceFile[]; 239 | 240 | sourceFiles.forEach(sourceFile => { 241 | if (contains(newSourceFiles, sourceFile)) { 242 | return; 243 | } 244 | 245 | // 不在编译目标文件范围内的老文件缓存数据被清掉 246 | if (sourceFile.fileWatcher) { 247 | sourceFile.fileWatcher.close(); 248 | sourceFile.fileWatcher = undefined; 249 | } 250 | }); 251 | } 252 | 253 | cachedProgram = program; 254 | } 255 | 256 | function sourceFileChanged(sourceFile: SourceFile, removed?: boolean) { 257 | if (sourceFile.fileWatcher) { 258 | sourceFile.fileWatcher.close(); 259 | sourceFile.fileWatcher = undefined; 260 | } 261 | 262 | if (removed) { 263 | rootFileNames.splice(rootFileNames.indexOf(sourceFile.fileName), 1); 264 | } 265 | 266 | startTimerForRecompilation(); 267 | } 268 | 269 | function configFileChanged() { 270 | // 因为项目配置文件的改动,所以 不在使用缓存数据 271 | setCachedProgram(undefined); 272 | cachedConfigFileText = undefined; 273 | 274 | startTimerForRecompilation(); 275 | } 276 | 277 | function watchedDirectoryChanged(fileName: string) { 278 | if (fileName && !isSupportedSourceFileName(fileName)) { 279 | return; 280 | } 281 | 282 | if (timerHandleForDirectoryChanges) { 283 | clearTimeout(timerHandleForDirectoryChanges); 284 | } 285 | 286 | timerHandleForDirectoryChanges = setTimeout(directoryChangeHandler, 250); 287 | } 288 | 289 | function directoryChangeHandler() { 290 | const parsedCommandLine = parseConfigFile() as ParsedCommandLine; 291 | const newFileNames = parsedCommandLine.fileNames.map(compilerHost.getCanonicalFileName); 292 | const canonicalRootFileNames = rootFileNames.map(compilerHost.getCanonicalFileName); 293 | 294 | if (!arrayIsEqualTo(newFileNames.sort(), canonicalRootFileNames.sort())) { 295 | setCachedProgram(undefined); 296 | startTimerForRecompilation(); 297 | } 298 | } 299 | 300 | function startTimerForRecompilation() { 301 | if (timerHandleForRecompilation) { 302 | clearTimeout(timerHandleForRecompilation); 303 | } 304 | 305 | timerHandleForRecompilation = setTimeout(recompile, 250); 306 | } 307 | 308 | function recompile() { 309 | timerHandleForRecompilation = undefined; 310 | 311 | reportWatchDiagnostic({ 312 | messageText: 'File change detected. Starting incremental compilation...' 313 | } as Diagnostic); 314 | 315 | performCompilation(); 316 | } 317 | 318 | function compile(fileNames: string[], compilerOptions: CompilerOptions, compilerHost: CompilerHost) { 319 | const program = createProgram(fileNames, compilerOptions, compilerHost); 320 | const exitStatus = compilerProgram(); 321 | 322 | return { 323 | program, 324 | exitStatus 325 | }; 326 | 327 | function compilerProgram() { 328 | let diagnostics: Diagnostic[]; 329 | diagnostics = program.getSyntacticDiagnostics(); 330 | 331 | if (diagnostics.length === 0) { 332 | diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); 333 | 334 | if (diagnostics.length === 0) { 335 | diagnostics = program.getSemanticDiagnostics(); 336 | } 337 | } 338 | 339 | const emitOutput = program.emit( 340 | undefined, 341 | undefined, 342 | undefined, 343 | undefined, 344 | { 345 | after: [ 346 | transformPathMapping 347 | ] 348 | } 349 | ); 350 | 351 | diagnostics = diagnostics.concat(emitOutput.diagnostics); 352 | 353 | reportDiagnostics(diagnostics); 354 | 355 | if (emitOutput.emitSkipped && diagnostics.length > 0) { 356 | return ExitStatus.DiagnosticsPresent_OutputsSkipped; 357 | } else if (diagnostics.length > 0) { 358 | return ExitStatus.DiagnosticsPresent_OutputsGenerated; 359 | } 360 | 361 | return ExitStatus.Success; 362 | } 363 | } 364 | 365 | function reportDiagnostic(diagnostic: Diagnostic, host?: FormatDiagnosticsHost) { 366 | reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); 367 | } 368 | 369 | function reportDiagnostics(diagnostics: Diagnostic[], host?: FormatDiagnosticsHost): void { 370 | for (const diagnostic of diagnostics) { 371 | reportDiagnostic(diagnostic, host); 372 | } 373 | } 374 | } 375 | 376 | function reportDiagnosticSimply(diagnostic: Diagnostic, host: FormatDiagnosticsHost) { 377 | sys.write(formatDiagnostics([diagnostic], host)); 378 | } 379 | 380 | function formatAndReset(text: string, formatStyle: string) { 381 | return formatStyle + text + resetEscapeSequence; 382 | } 383 | 384 | function diagnosticCategoryText(category: DiagnosticCategory): string { 385 | const text = DiagnosticCategory[category].toLowerCase(); 386 | 387 | let colorWrapper: (text?: string) => string = String; 388 | 389 | switch (category) { 390 | case DiagnosticCategory.Warning: colorWrapper = Chalk.yellow; break; 391 | case DiagnosticCategory.Error: colorWrapper = Chalk.red; break; 392 | case DiagnosticCategory.Message: colorWrapper = Chalk.blue; break; 393 | } 394 | 395 | return colorWrapper(text); 396 | } 397 | 398 | function reportDiagnosticPretty(diagnostic: Diagnostic, host: FormatDiagnosticsHost) { 399 | let output: string = ''; 400 | 401 | // 排版 出错位置定位 打印信息 402 | if (diagnostic.file) { 403 | const { start, length, file } = diagnostic; 404 | const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); 405 | const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); 406 | const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; 407 | const relativeFileName = host ? getRelativePath(host.getCurrentDirectory(), file.fileName) : file.fileName; 408 | 409 | const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; 410 | let gutterWidth = (lastLine + 1 + '').length; 411 | 412 | if (hasMoreThanFiveLines) { 413 | gutterWidth = Math.max(ellipsis.length, gutterWidth); 414 | } 415 | 416 | output += NL; 417 | for (let i = firstLine; i <= lastLine; i++) { 418 | if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { 419 | output += 420 | (formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) 421 | + gutterSeparator 422 | + NL); 423 | 424 | i = lastLine - 1; 425 | } 426 | 427 | const lineStart = getPositionOfLineAndCharacter(file, i, 0); 428 | const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; 429 | let lineContent = file.text.slice(lineStart, lineEnd); 430 | lineContent = lineContent.replace(/\s+$/g, ''); 431 | lineContent = lineContent.replace('\t', ' '); 432 | 433 | output += 434 | (`\u001b[100;30m${padLeft(i + 1 + '', gutterWidth)}\u001b[0m` 435 | + gutterSeparator 436 | + lineContent 437 | + NL 438 | // ---- 439 | + formatAndReset(padLeft('', gutterWidth), gutterStyleSequence) 440 | + gutterSeparator); 441 | 442 | output += redForegroundEscapeSequence; 443 | if (i === firstLine) { 444 | const lastCharForLine = i === lastLine ? lastLineChar : undefined; 445 | 446 | output += lineContent.slice(0, firstLineChar).replace(/\S/g, ' '); 447 | output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, '~'); 448 | } else if (i === lastLine) { 449 | output += lineContent.slice(0, lastLineChar).replace(/./g, '~'); 450 | } else { 451 | output += lineContent.replace(/./g, '~'); 452 | } 453 | output += resetEscapeSequence; 454 | 455 | output += sys.newLine; 456 | } 457 | 458 | output += sys.newLine; 459 | output += `${relativeFileName}(${firstLine + 1},${firstLineChar + 1}): `; 460 | } 461 | 462 | output += 463 | (`${diagnosticCategoryText(diagnostic.category)} ` 464 | + `TS${diagnostic.code} ${flattenDiagnosticMessageText(diagnostic.messageText, NL)}` 465 | + NL 466 | + NL); 467 | 468 | sys.write(output); 469 | } 470 | 471 | function reportEmittedFiles(files: string[]): void { 472 | if (!files || files.length === 0) { 473 | return; 474 | } 475 | 476 | const currentDir = sys.getCurrentDirectory(); 477 | 478 | for (const file of files) { 479 | const filepath = Path.resolve(currentDir, file); 480 | 481 | sys.write(`TSFILE: ${filepath}${NL}`); 482 | } 483 | } 484 | 485 | function reportWatchDiagnostic(diagnostic: Diagnostic) { 486 | let output = new Date().toLocaleTimeString() + ' - '; 487 | 488 | if (diagnostic.file) { 489 | const loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); 490 | output += `${diagnostic.file.fileName}(${loc.line + 1},${loc.character + 1}): `; 491 | } 492 | 493 | output += 494 | (`${flattenDiagnosticMessageText(diagnostic.messageText, NL)}` 495 | + NL 496 | + NL 497 | + NL); 498 | 499 | sys.write(output); 500 | } 501 | -------------------------------------------------------------------------------- /src/util/tsc/transform-path-mapping.ts: -------------------------------------------------------------------------------- 1 | import * as Path from 'path'; 2 | 3 | import { 4 | EmitHint, 5 | Expression, 6 | Identifier, 7 | ImportDeclaration, 8 | ModuleKind, 9 | Node, 10 | SourceFile, 11 | SyntaxKind, 12 | TransformationContext, 13 | getOriginalNode, 14 | sys 15 | } from 'typescript'; 16 | 17 | import { 18 | getEmitModuleKind, 19 | getRelativePath 20 | } from './helper'; 21 | 22 | import { 23 | typeScriptSupportFileExtRegx 24 | } from './types'; 25 | 26 | export default function transformPathMapping(context: TransformationContext) { 27 | const compilerOptions = context.getCompilerOptions(); 28 | const baseUrl = compilerOptions.baseUrl || sys.getCurrentDirectory(); 29 | const moduleKind = getEmitModuleKind(compilerOptions); 30 | const isCommonJSModuleKind = moduleKind === ModuleKind.CommonJS; 31 | 32 | let previousOnSubstituteNode: typeof context.onSubstituteNode; 33 | let currentSourceFile: SourceFile; 34 | let needSubstitutionModulePath = false; 35 | let moduleFileNameMapping: Map; 36 | 37 | // 只针对 uniapp 目前选择的JS模板管理形式 38 | if (isCommonJSModuleKind) { 39 | moduleFileNameMapping = new Map(); 40 | previousOnSubstituteNode = context.onSubstituteNode; 41 | 42 | context.onSubstituteNode = onSubstituteNode; 43 | 44 | // 开放需要被替换的语言语法对象 45 | context.enableSubstitution(SyntaxKind.StringLiteral); 46 | context.enableSubstitution(SyntaxKind.RequireKeyword); 47 | } 48 | 49 | return transformSourceFile; 50 | 51 | function transformSourceFile(node: SourceFile) { 52 | currentSourceFile = node; 53 | return node; 54 | } 55 | 56 | function onSubstituteNode(hint: EmitHint, node: Node) { 57 | node = previousOnSubstituteNode(hint, node); 58 | 59 | if (node.kind === SyntaxKind.Identifier) { 60 | let identifier = node as Identifier; 61 | 62 | // 找到 require(...) 标记 63 | if (identifier.originalKeywordKind === SyntaxKind.RequireKeyword) { 64 | needSubstitutionModulePath = true; 65 | return node; 66 | } 67 | 68 | } 69 | 70 | // 处理和替换 require(...) 参数 71 | if (needSubstitutionModulePath) { 72 | needSubstitutionModulePath = false; 73 | return substitutionModulePath(node); 74 | } 75 | 76 | return node; 77 | } 78 | 79 | function substitutionModulePath(node: Node) { 80 | let identifier = node as Identifier; 81 | let moduleFileName = moduleFileNameMapping.get(identifier.text); 82 | 83 | if (moduleFileName) { 84 | identifier.text = moduleFileName; 85 | return node; 86 | } 87 | 88 | // 危险使用,因为 resolvedModules 并不是 typescript 开放的api 89 | let resolvedModules = (currentSourceFile as any).resolvedModules; 90 | 91 | if (!resolvedModules) { 92 | return node; 93 | } 94 | 95 | let resolvedModule = resolvedModules.get(identifier.text); 96 | 97 | // 忽略 node.js 核心 和 node_modules内的 模板 98 | if (!resolvedModule || !resolvedModule.resolvedFileName || resolvedModule.isExternalLibraryImport) { 99 | return node; 100 | } 101 | 102 | moduleFileName = getRelativePath(baseUrl, resolvedModule.resolvedFileName) 103 | .replace(typeScriptSupportFileExtRegx, '.js'); 104 | 105 | moduleFileNameMapping.set(identifier.text, moduleFileName); 106 | 107 | // 非推介方式实现的替换 108 | identifier.text = moduleFileName; 109 | 110 | return node; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/util/tsc/types.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Identifier as _Identifier, 3 | Node, 4 | PrimaryExpression, 5 | SyntaxKind 6 | } from 'typescript'; 7 | 8 | export const typeScriptSupportFileExtRegx = /\.?(?:d\.ts|ts|tsx)$/i; 9 | 10 | export const enum TransformFlags { 11 | None = 0, 12 | 13 | ContainsTypeScript = 1 << 1, 14 | 15 | HasComputedFlags = 1 << 29, 16 | 17 | TypeExcludes = ~ContainsTypeScript 18 | } 19 | 20 | export interface Node extends Node { 21 | transformFlags?: any; 22 | emitNode?: any; 23 | } 24 | 25 | export const enum GeneratedIdentifierKind { 26 | None, 27 | Auto, 28 | Loop, 29 | Unique, 30 | Node, 31 | } 32 | 33 | export interface Identifier extends _Identifier { 34 | autoGenerateKind?: GeneratedIdentifierKind; 35 | autoGenerateId?: number; 36 | } 37 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2015", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "declaration": false, 7 | "strictNullChecks": true, 8 | "noImplicitAny": true, 9 | "noImplicitReturns": true, 10 | "noImplicitThis": true, 11 | "removeComments": true, 12 | "skipDefaultLibCheck": true, 13 | "noEmitOnError": false, 14 | "preserveConstEnums": true, 15 | "noLib": false, 16 | "sourceMap": true, 17 | "outDir": "./dist", 18 | "experimentalDecorators": true, 19 | "emitDecoratorMetadata": true, 20 | "pretty": true, 21 | "listFiles": false 22 | }, 23 | "include": [ 24 | "./typings/**/*", 25 | "./src/**/*" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "vts", 3 | "rules": { 4 | "no-bitwise": false, 5 | "prefer-template": false, 6 | "prefer-const": false, 7 | "no-require-imports": false, 8 | "no-var-requires": false, 9 | "trailing-comma": [ false ], 10 | "return-undefined": false, 11 | "no-unbound-method": false, 12 | "variable-name": [ 13 | true, 14 | "ban-keywords", 15 | "allow-pascal-case", 16 | "allow-trailing-underscore", 17 | "allow-leading-underscore" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /typings/extends/cli-spinner/cli-spinner.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'cli-spinner' { 2 | export class Spinner { 3 | /** Creates a new spinner object with the default options. */ 4 | constructor(name: string); 5 | 6 | /** Starts the spinner. */ 7 | start(): void; 8 | 9 | /** Stops the spinner. Accepts a Boolean parameter to clean the console. */ 10 | stop(clean?: boolean): void; 11 | 12 | /** Sets the spinner string. Accepts either a String or an Integer index to reference the built-in spinners. */ 13 | setSpinnerString(spinnerString: number | string): void; 14 | 15 | /** Sets the spinner animation speed. */ 16 | setSpinnerDelay(spinnerDelay: number): void; 17 | 18 | /** Sets the default spinner string for all newly created instances. Accepts either a String or an Integer index to reference the built-in spinners. */ 19 | setDefaultSpinnerString(spinnerString: number | string): void; 20 | 21 | /** Sets the default spinner delay for all newly created instances. */ 22 | setDefaultSpinnerDelay(spinnerDelay: number): void; 23 | 24 | /** Sets the spinner title. Use printf-style strings to position the spinner. */ 25 | setSpinnerTitle(spinnerTitle: string): void; 26 | 27 | /** Returns true/false depending on whether the spinner is currently spinning. */ 28 | isSpinning(): boolean; 29 | } 30 | } --------------------------------------------------------------------------------