首發於: https://luoyangfu.com/article...
下面假設在tsc 執行目錄中有以下配置:
{ "compilerOptions": { /* Basic Options */ "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */, "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, "plugins": [{ "name": "typescript-tslint-plugin" }], // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "sourceMap": true /* Generates corresponding '.map' file. */, // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "dist" /* Redirect output structure to the directory. */, // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, // "baseUrl": "." /* Base directory to resolve non-absolute module names. */, // "paths": { // "config/*": ["src/config/*"], // "controllers/*": ["./src/controllers/*"], // "db/*": ["./src/db/*"], // "middlewares/*": ["./src/middlewares/*"], // "routes/*": ["./src/routes/*"], // "services/*": ["./src/services/*"], // "static/*": ["./src/static/*"], // "templates/*": ["./src/templates/*"], // "tools/*": ["./src/tools/*"], // "src/*": ["./src/*"] // } /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */, // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ "traceResolution": false, "typeRoots": [ "node_modules/@types", "src/typings" ] /* List of folders to include type definitions from. */, // "types": [], /* Type declaration files to be included in compilation. */ "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ "inlineSourceMap": true /* Emit a single file with source maps instead of having a separate file. */, // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ }, "include": ["src/**/*"] }
上面就爲一個typescript的簡單配置。(PS: 可直接複製使用哦)javascript
在代碼裏面若是須要把 typescript
轉化成 javascript
時候,咱們須要執行下面命令java
$ tsc index.ts
這裏 npx 爲包執行命令的bash.
咱們經過這樣方式就能夠把 ts 代碼,轉化成了 js代碼,若是說咱們須要時刻監聽代碼修改,而後根據代碼的改變來轉化呢?node
$ tsc index.ts --watch
經過watch 表示來實現監聽,看下圖
react
這裏會默認顯示兩條信息,而且會清空當前控制檯。git
若是說咱們有多條命令須要同時執行呢?看下面圖片來看:es6
這裏就會不斷閃爍。每次修改也會清空,想觀察控制檯就很難觀察。so,須要一種方式,既要監聽typescript自動編譯,還須要可以自定義處理輸出。github
這裏就須要去學習一下typescript編譯的API。typescript
查找配置文件路徑
代碼申明:express
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined;
ts.sys.fileExists
, 這個函數傳遞一個路徑判斷文件是否存在tsocnfig.json
這裏須要說一下是的,typescript可使用不一樣的代碼創造器的 策略
去建立程序json
前兩種代碼創造器策略是創造可運行的程序,他們都是使用一種增量策略,僅僅檢查內容發生改變而且觸發的文件或者那些依賴以及改變而後影響以前產生的代碼結果。最後一個使用普通程序,在每次更改後進行完整類型檢查。前兩種區別在於觸發個點上。對於純類型檢查場景或者第三方工具、進程手動觸發使用 ts.createSemanticDiagnosticsBuilderProgram
或許更合適。
代碼申明:
function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): SemanticDiagnosticsBuilderProgram; function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>, projectReferences?: ReadonlyArray<ProjectReference>): SemanticDiagnosticsBuilderProgram;
這裏又兩種形式代碼申明, 可是這兩種形式其實在後續都說明,又其餘代碼傳入,沒必要手動傳遞.
這裏就是建立 watch 的typescript 腳本API了。這裏是實現了
tsc -w
這個命令.
代碼申明:
function createWatchCompilerHost<T extends BuilderProgram>(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile<T>; function createWatchCompilerHost<T extends BuilderProgram>(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray<ProjectReference>): WatchCompilerHostOfFilesAndCompilerOptions<T>;
也有兩種形式申明根據實際狀況,我這裏選擇第一種函數形式:
ts.system
便可ts.createSemanticDiagnosticsBuilderProgram
便可.Diagnostic
對象,包含當前代碼的診斷信息,報錯的代碼片斷等Diagnostic
對象,經過 ts.formatDiagnostic
能夠格式化當前對象,獲得一個以下類型的消息: message TS1234: xxxx
這樣的提示信息這裏返回就返回一個 WatchCompilerHostOfConfigFile
對象
建立一個程序監聽器
代碼申明:
function createWatchProgram<T extends BuilderProgram>(host: WatchCompilerHostOfConfigFile<T>): WatchOfConfigFile<T>;
在上面一個函數 createWatchCompilerHost
建立成功後須要有以下操做:
const host = ts.createWatchCompilerHost( configPath, {}, ts.sys, createProgram, reportDiagnostic, reportWatchStatusChanged ); const origCreateProgram = host.createProgram; host.createProgram = (rootNames, options, host, oldProgram) => { consola.info("We're about to create the program!"); return origCreateProgram(rootNames, options, host, oldProgram); }; const origPostProgramCreate = host.afterProgramCreate; host.afterProgramCreate = (program) => { consola.info('We finished making the program!'); origPostProgramCreate(program); }; ts.createWatchProgram(host);
在 host
上有兩個屬性分別是: createProgram
和 afterProgramCreate
。 這兩個屬性,咱們若是要想知道對應階段,例如創造程序開始和完成就須要使用閉包包裹一下便可。正如上面代碼.
const ts = require('typescript'); const consola = require('consola'); const formatHost = { getCanonicalFileName: (path) => path, getCurrentDirectory: ts.sys.getCurrentDirectory, getNewLine: () => ts.sys.newLine, }; function watchMain() { const configPath = ts.findConfigFile(/*searchPath*/ './', ts.sys.fileExists, 'tsconfig.json'); if (!configPath) { throw new Error("Could not find a valid 'tsconfig.json'."); } const createProgram = ts.createSemanticDiagnosticsBuilderProgram; const host = ts.createWatchCompilerHost( configPath, {}, ts.sys, createProgram, reportDiagnostic, reportWatchStatusChanged ); const origCreateProgram = host.createProgram; host.createProgram = (rootNames, options, host, oldProgram) => { consola.info("We're about to create the program!"); return origCreateProgram(rootNames, options, host, oldProgram); }; const origPostProgramCreate = host.afterProgramCreate; host.afterProgramCreate = (program) => { consola.info('We finished making the program!'); origPostProgramCreate(program); }; ts.createWatchProgram(host); } function reportDiagnostic(diagnostic) { consola.error( 'Error', diagnostic.code, ':', ts.flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine()) ); } function reportWatchStatusChanged(diagnostic) { let message = ts.formatDiagnostic(diagnostic, formatHost); if (message.indexOf('TS6194') > 0) { message = message.replace(/message\sTS[0-9]{4}:(.+)(\s+)$/, '$1'); consola.ready({ message, badge: true }); } } watchMain();
上面就是完整的執行typescript編譯監聽腳本
consola 沒寫錯,這是一個支持nodejs 和 瀏覽器的控制檯日誌輸入器,支持顏色輸出哦。
看效果:
基本達到想要結果。後面還有什麼好玩的歡迎交流。