55 * - 生成 style.js 和 index.scss
66 */
77
8- const { createReadStream, createWriteStream, writeFileSync } = require ( 'fs' ) ;
8+ const { createReadStream, createWriteStream, writeFileSync, ensureDirSync } = require ( 'fs-extra ' ) ;
99const babel = require ( '@babel/core' ) ;
1010const glob = require ( 'glob' ) ;
1111const mkdirp = require ( 'mkdirp' ) ;
1212const path = require ( 'path' ) ;
1313const rimraf = require ( 'rimraf' ) ;
14+ const ts = require ( 'typescript' ) ;
1415
1516module . exports = function componentBuild ( { babelConfig, rootDir, log } ) {
1617 const srcDir = path . join ( rootDir , 'src' ) ;
@@ -54,6 +55,7 @@ module.exports = function componentBuild({ babelConfig, rootDir, log }) {
5455 filename : file ,
5556 } ) ) ;
5657 writeFileSync ( path . format ( destData ) , code , 'utf-8' ) ;
58+ dtsCompile ( { filePath : file , sourceFile : source , destPath : libDir } ) ;
5759 log . info ( `Compile ${ file } ` ) ;
5860 }
5961
@@ -69,4 +71,34 @@ module.exports = function componentBuild({ babelConfig, rootDir, log }) {
6971 log . info ( `Copy ${ file } ` ) ;
7072 } ) ;
7173 }
74+ // https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#getting-the-dts-from-a-javascript-file
75+ function dtsCompile ( { filePath, sourceFile, destPath } ) {
76+ const REG_TS = / \. ( t s x ? ) $ / ;
77+ const isTS = REG_TS . test ( filePath ) ;
78+ if ( ! isTS ) return ;
79+ const compilerOptions = {
80+ allowJs : true ,
81+ declaration : true ,
82+ emitDeclarationOnly : true ,
83+ } ;
84+ const dtsPath = filePath . replace ( REG_TS , '.d.ts' ) ;
85+ const targetPath = path . join ( destPath , dtsPath ) ;
86+ // Create a Program with an in-memory emit
87+ let createdFiles = { } ;
88+ const host = ts . createCompilerHost ( compilerOptions ) ;
89+ host . writeFile = ( fileName , contents ) => createdFiles [ fileName ] = contents ;
90+ // Prepare and emit the d.ts files
91+ const program = ts . createProgram ( [ sourceFile ] , compilerOptions , host ) ;
92+ program . emit ( ) ;
93+ const fileNamesDTS = sourceFile . replace ( REG_TS , '.d.ts' ) ;
94+ const content = createdFiles [ fileNamesDTS ] ;
95+ // write file
96+ if ( content ) {
97+ ensureDirSync ( path . dirname ( targetPath ) ) ;
98+ writeFileSync ( targetPath , content , 'utf-8' ) ;
99+ log . info ( `Generate ${ path . basename ( targetPath ) } ` ) ;
100+ }
101+ // release
102+ createdFiles = null ;
103+ }
72104} ;
0 commit comments