1
- import * as assert from 'node:assert' ;
2
- import * as util from 'node:util' ;
1
+ import assert from 'node:assert' ;
2
+ import util from 'node:util' ;
3
3
4
- import * as ts from 'typescript' ;
4
+ import ts from 'typescript' ;
5
5
6
6
/**
7
7
* Adds extension to all paths imported inside MJS files
8
8
*
9
9
* Transforms:
10
10
*
11
11
* ```
12
- * import { foo } from './bar';
13
- * export { foo } from './bar';
12
+ * import { foo } from './bar.js ';
13
+ * export { foo } from './bar.js ';
14
14
* ```
15
15
*
16
16
* to:
17
17
*
18
18
* ```
19
- * import { foo } from './bar.mjs ';
20
- * export { foo } from './bar.mjs ';
19
+ * import { foo } from './bar.ts ';
20
+ * export { foo } from './bar.ts ';
21
21
* ```
22
22
*
23
23
*/
24
- export function addExtensionToImportPaths ( config : { extension : string } ) {
24
+ export function changeExtensionInImportPaths ( config : { extension : string } ) {
25
25
const { extension } = config ;
26
26
return ( context : ts . TransformationContext ) => {
27
27
const { factory } = context ;
@@ -35,13 +35,15 @@ export function addExtensionToImportPaths(config: { extension: string }) {
35
35
function visitNode ( node : ts . Node ) : ts . Node {
36
36
const source : string | undefined = ( node as any ) . moduleSpecifier ?. text ;
37
37
if ( source ?. startsWith ( './' ) || source ?. startsWith ( '../' ) ) {
38
+ const newSource = source . replace ( / \. j s $ / , extension ) ;
39
+
38
40
if ( ts . isImportDeclaration ( node ) ) {
39
41
return factory . updateImportDeclaration (
40
42
node ,
41
43
node . decorators ,
42
44
node . modifiers ,
43
45
node . importClause ,
44
- ts . createStringLiteral ( source + extension ) ,
46
+ factory . createStringLiteral ( newSource ) ,
45
47
node . assertClause ,
46
48
) ;
47
49
}
@@ -52,7 +54,7 @@ export function addExtensionToImportPaths(config: { extension: string }) {
52
54
node . modifiers ,
53
55
node . isTypeOnly ,
54
56
node . exportClause ,
55
- ts . createStringLiteral ( source + extension ) ,
57
+ factory . createStringLiteral ( newSource ) ,
56
58
node . assertClause ,
57
59
) ;
58
60
}
0 commit comments