@@ -11,7 +11,7 @@ import * as ts from 'typescript';
11
11
* @deprecated From 0.9.0
12
12
*/
13
13
export function testImportTslib ( content : string ) {
14
- const regex = / v a r ( _ _ e x t e n d s | _ _ d e c o r a t e | _ _ m e t a d a t a | _ _ p a r a m ) = \( .* \r ? \n ( .* \r ? \n ) * \} ; / ;
14
+ const regex = / v a r ( _ _ e x t e n d s | _ _ d e c o r a t e | _ _ m e t a d a t a | _ _ p a r a m ) = \( .* \r ? \n \s + ( .* \r ? \n ) * \s * \} ; / ;
15
15
16
16
return regex . test ( content ) ;
17
17
}
@@ -21,10 +21,12 @@ export function getImportTslibTransformer(): ts.TransformerFactory<ts.SourceFile
21
21
22
22
const transformer : ts . Transformer < ts . SourceFile > = ( sf : ts . SourceFile ) => {
23
23
24
+ const tslibImports : ( ts . VariableStatement | ts . ImportDeclaration ) [ ] = [ ] ;
25
+
24
26
// Check if module has CJS exports. If so, use 'require()' instead of 'import'.
25
27
const useRequire = / e x p o r t s .\S + \s * = / . test ( sf . getText ( ) ) ;
26
28
27
- const visitor : ts . Visitor = ( node : ts . Node ) : ts . Node => {
29
+ const visitor : ts . Visitor = ( node : ts . Node ) : ts . Node | undefined => {
28
30
29
31
// Check if node is a TS helper declaration and replace with import if yes
30
32
if ( ts . isVariableStatement ( node ) ) {
@@ -35,23 +37,36 @@ export function getImportTslibTransformer(): ts.TransformerFactory<ts.SourceFile
35
37
36
38
if ( isHelperName ( name ) ) {
37
39
// TODO: maybe add a few more checks, like checking the first part of the assignment.
40
+ const tslibImport = createTslibImport ( name , useRequire ) ;
41
+ tslibImports . push ( tslibImport ) ;
38
42
39
- return createTslibImport ( name , useRequire ) ;
43
+ return undefined ;
40
44
}
41
45
}
42
46
}
43
47
44
48
return ts . visitEachChild ( node , visitor , context ) ;
45
49
} ;
46
50
47
- return ts . visitEachChild ( sf , visitor , context ) ;
51
+ const sfUpdated = ts . visitEachChild ( sf , visitor , context ) ;
52
+
53
+ // Add tslib imports before any other statement
54
+ return tslibImports . length > 0
55
+ ? ts . updateSourceFileNode ( sfUpdated , [
56
+ ...tslibImports ,
57
+ ...sfUpdated . statements ,
58
+ ] )
59
+ : sfUpdated ;
48
60
} ;
49
61
50
62
return transformer ;
51
63
} ;
52
64
}
53
65
54
- function createTslibImport ( name : string , useRequire = false ) : ts . Node {
66
+ function createTslibImport (
67
+ name : string ,
68
+ useRequire = false ,
69
+ ) : ts . VariableStatement | ts . ImportDeclaration {
55
70
if ( useRequire ) {
56
71
// Use `var __helper = /*@__PURE__*/ require("tslib").__helper`.
57
72
const requireCall = ts . createCall ( ts . createIdentifier ( 'require' ) , undefined ,
0 commit comments